About FormData File Upload
About file upload
In the modern era, use input file to select a file, then pass the DOM object into FormData.
var filedata = document.getElementById('file');
var formData= new FormData();
formData.append('file',filedata);
var xhr = new XMLHttpRequest();
xhr.open('post','url',true);
xhr.send(formData);
xhr.onreadystatechange= function(){
if(xhr.readyState = 4 &&xhr.staus == 200){
do something....
}
}
or
// assuming the HTML already has a form with an input type="file"
var form = document.getElementById('form');
// just pass it into FormData
var formData= new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('post','url',true);
xhr.send(formData);
xhr.onreadystatechange= function(){
if(xhr.readyState = 4 &&xhr.staus == 200){
do something....
}
}
In the era before FormData, we used form to upload files.
Create a form with JavaScript, put a few inputs inside, then submit it — that also works for file upload.