FormData will always be sent as multipart/form-data
.
If you just post normal form data without uploading files, multipart/form-data
is better.
If you want to upload files, multipart/form-data
is better.
If you have to upload files with x-www-form-urlencoded
, you should convert the files data to string data via base64 etc, and write special server-end code. This is strongly not recommended.
If you want to send FormData as x-www-form-urlencoded
, there are 2 ways at least.
// use xhr API
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send(new URLSearchParams(formDataObj));
// or use fetch API
fetch(url, {
method: 'post',
body: new URLSearchParams(formDataObj)
});
2. Encode the content items to querystring.
function urlencodeFormData(fd){
var s = '';
function encode(s){ return encodeURIComponent(s).replace(/%20/g,'+'); }
for(var pair of fd.entries()){
if(typeof pair[1]=='string'){
s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
}
}
return s;
}
var form = document.myForm;
xhr.open('POST', form.action, false);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send(urlencodeFormData(new FormData(form)));
you can also use URLSearchParams like this:
function urlencodeFormData(fd){
var params = new URLSearchParams(fd);
return params.toString();
}
For old browsers which doesn't support URLSearchParams API, you can use one of polyfills: