How can I create the following result using FormData
------WebKitFormBoundaryOmz20xyMCkE27rN7
Content-Disposition: form-data; name="data";
Content-Type: application/json
{
"description": "description"
}
------WebKitFormBoundaryOmz20xyMCkE27rN7
Content-Disposition: form-data; name="file"; filename="image.jpg"
Content-Type: image/jpeg
FILE_DATA
------WebKitFormBoundaryOmz20xyMCkE27rN7
I am using
const formData = new FormData();
const data = new Blob([JSON.stringify({
description: 'description',
})], {
type: 'application/json'
});
formData.set('data', data);
formData.set('file', file);
it generate
------WebKitFormBoundaryOmz20xyMCkE27rN7
Content-Disposition: form-data; name="data"; filename="blob"
Content-Type: application/json
{
"description": "description"
}
------WebKitFormBoundaryOmz20xyMCkE27rN7
Content-Disposition: form-data; name="file"; filename="image.jpg"
Content-Type: image/jpeg
FILE_DATA
------WebKitFormBoundaryOmz20xyMCkE27rN7
As you can see we have a filename="blob"
in JSON part , I want to remove it
I want to have a data
field in my multipart data not a data
file
Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.
Yes you can, you can append to formData objects.
append() The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
When you do
new Blob([JSON.stringify({
description: 'description',
})], {
type: 'application/json'
})
What you are really generating is a file, an UTF-8 text file, whose content will be {description:'description}
encoded in UTF-8.
So when you append it to your FormData, it is passed as a file, with the one particularity that you did set its Content-Type to application/json
.
If you wish to send this data as part of the form-data's data in plain-text, that your server will be able to parse from the post-data directly, then just append your string as a key of your FormData:
const data = JSON.stringify({
description: 'description',
})
const fd = new FormData();
// append directly as part of the postData in plain text
fd.append('data', data);
console.log(...fd); // [key, value]
There is another option which make it work for me
const dto_object = new Blob([JSON.stringify({
description: 'description',
})], {
type: 'application/json'
})
Then
formData.append("my_dto", dto_object, ""); // empty file name doesn't make it dissapear but it seems most server accepts it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With