can i send multipart/form-data as json file without converting formdata before sending post request to backend.
Yes, you can do that using axios instance you can send post request without convert your object to form data. After axios versions v0.27.0 automatic your json data as multipart form-data you do not need to take extra pressure for sending binary data.
You may check my implementaions below where i upload file as json objects.here, in data sections thumbnail is a file type data.
import axios from 'axios';
const postJsonFile = async () => {
const url = 'https://example.com/api/upload';
const data = {
"title": "Title",
"thumbnail": {
"0": { File {name: 'bkash.jpeg', lastModified:
1683520805146, lastModifiedDate: Mon May 08 2023 10:40:05
GMT+0600 (Bangladesh Standard Time), webkitRelativePath:
'', size: 43133, …}
length:
1[[Prototype]]
:
FileList
}
},
"description": "<p>Descriptions</p>",
"skill_level": [
"BEGINNER",
"ADVANCE"
],
"demo_videos": [
"https://youtu.be/PsaXRgCibfU"
]
}
try {
const response = await axios.post(url, data, {
headers: {
'Content-Type': 'multipart/form-data',
},
formSerializer: {
// Ensures array indices are included in serialized keys
indexes: true,
},
});
console.log('Response:', response.data);
} catch (error) {
console.error('Error:', error.response?.data || error.message);
}
};
postJsonFile();
Note: you may not need to add formSerializer but if your backend written on python during that time you need to serialize data from frontend otherwise it will not works properly Or you may need to added extra code into your backend.
Learn more you may check:
Top comments (0)