I want to upload a file to the server via an API. On documenter.getpostman, this is how to use the API
--form 'type="1"' \
--form 'user_id="1"' \
--form 'file=@"/C:/Users/xxx/Downloads/xxx.postman_collection.json"'
This is what I did
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
contains the files from the input type="file"
, and i'm able to see its contents when I log it to the console, but logging fd
which carries the form data always returns an empty object. And type: this.uploadType, user_id: this.user_id
are other params i'm sending to the api
The request always returns 400(bad request)
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)
I'm not sure if the API wants the path to the file, because, I have tried hard coding the file path into the request like this
let response = await this.$axios.post('/staff/customer/add/document', {
type: this.uploadType,
user_id: this.user_id,
file: '/home/myDevice/Downloads/download.jpeg',
})
but still, get the same response. Please I need all the help i can get, thanks.
Solved this using @CBroe comment.
I appended both type
and user_id
into the formData
, and then passed in formData
object.
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)
}