Recent searches
No recent searches
Uploading attachment using JavaScript
Answered
Posted Mar 17, 2021
I am trying to upload an attachment (dummy.png), the response is that the attachment has been created as I get a 201 response with a token.
I then attach the token to the uploads array before submitting a new ticket. The issue I am having is when I view the ticket, the attachment is corrupted. I am wondering whether it is how i am uploading the attachment in the first place.
This is my header below for uploading an attachment. Can someone let me know if there is an issue here?
Thank you.
const response = await axios.post(`uploads.json?filename=dummy.png`, body, {
baseURL: '/api/v2',
headers: {
common: {
Accept: 'application/json',
'Content-Type': 'image/png',
mode: 'no-cors',
Authorization: `Basic ${process.env.token}`,
},
},
withCredentials: true,
});
0
5
5 comments
Sushant A
Hi james,
Can you try this?
Replace Content-Type
with
Hope this helps!!
-sushant
0
James Smyth
Hello Sushant,
Thank you for your response but this still does not work. The image after uploading is still corrupt and can not be viewed.
Do you have a working example?
0
Sushant A
I haven't tried with Axios yet. but I have used attachment API in python scripts and it works as expected. you can give try with the postman client and check if that works for you and then you can troubleshoot the issue whether Axios is causing this or any other factors.
-sushant
0
FXDiamond
Hi @...
I'm using React with axios myself and I had the same issue which is now being resolved with the following:
First, the Content-Type must be binary, as Sushant suggested, only for the Upload API call. The Request API it will be the usual application/json:
Second, I don't think you've converted your uploaded file to base64. You must convert before attaching it to your axios body. This way it won't break.
I have found this code snippet which works like a charm: https://codesandbox.io/s/convert-file-to-base64-in-react-lqi1e
It's written for React, but you should be able to extract a JS version of it.
0
Nícola Gabriel
The solution that worked for me is:
1. Converting the image/video/file to a buffer first
2. Uploading the buffer as application/binary
The code is a bit big, but not hard to understand:
user selects file -> handleFileSelectAndUpload -> readFileAsBuffer -> handleImageUpload
1