I’m trying to upload an image as FormData to an API. I referred to the following thread.
https://forums.appgyver.com/t/uploading-file-to-directus-multipart-form-data/11271
My JavaScript function is below.
const {url, imagePath, token} = inputs
const formData = new FormData()
const blobResp = await fetch(imagePath)
const blob = await blobResp.blob()
console.log('blob: ', blob)
formData.append('file', blob)
const options = {
clientId: 'default',
extraction: {
'headerFields': ['senderName'],
'lineItemFields': ['description']
},
documentType: 'invoice'
};
formData.append('options', JSON.stringify(options))
try {
console.log('before sending request', formData)
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
},
body: formData
})
console.log('response: ', response)
const json = await response.json()
console.log('json: ', json)
return {id: json.id}
} catch (error) {
console.log(error)
const errorObj = {
code: '9',
message: 'something went wrong',
rawError: error
}
return [1, errorObj]
}
When I run the app, the logic fails at the fetch call below and an exception is caught.
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
},
body: formData
})
If I don’t add the blob to formData, API call is successful (though error is retuned, which is fine).
So I suspect something is wrong with the blob object. I’ve written almost the same code in Node.js and worked fine.
The image below is the console output of the formData.