Quiero subir un archivo al servidor a través de una API. En documenter.getpostman, así es como se usa la API
--form 'type="1"' \ --form 'user_id="1"' \ --form 'file=@"/C:/Users/xxx/Downloads/xxx.postman_collection.json"'Esto es lo que hice
try { const fd = new FormData() fd.append('file', this.dropFiles) let response = await this.$axios.post('/staff/customer/add/document', { type: this.uploadType, user_id: this.user_id, file: fd, }) console.log(response.data.success) } catch(err){ console.log(err) } this.dropFiles contiene los archivos del input type="file" , y puedo ver su contenido cuando lo registro en la consola, pero registrar fd que lleva los datos del formulario siempre devuelve un objeto vacío. Y type: this.uploadType, user_id: this.user_id son otros parámetros que estoy enviando a la API
La solicitud siempre devuelve 400 (solicitud incorrecta)
Error: Request failed with status code 400 at createError (createError.js?2d83:16) at settle (settle.js?467f:17) at XMLHttpRequest.onloadend (xhr.js?b50d:54)No estoy seguro de si la API quiere la ruta al archivo, porque he intentado codificar la ruta del archivo en la solicitud de esta manera
let response = await this.$axios.post('/staff/customer/add/document', { type: this.uploadType, user_id: this.user_id, file: '/home/myDevice/Downloads/download.jpeg', })pero aún así, obtener la misma respuesta. Por favor necesito toda la ayuda que pueda obtener, gracias.
Resolvió esto usando el comentario de @CBroe. Agregué type y user_id en formData y luego pasé el objeto formData .
try { const fd = new FormData() fd.append('file', this.dropFiles) fd.append('type', this.uploadType) fd.append('name', this.fileName) fd.append('user_id', this.user_id) let response = await this.$axios.post('/staff/customer/add/document', fd) console.log(response.data.success) } catch(err){ console.log(err) }