简体   繁体   中英

Sending a file via ajax

I want to send a file using HTTP POST request, the problem is that I can't do it - post and files arrays are empty on the serverside:

<input type="file" id="file"/>

let data = document.getElementById('file').files[0];
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", 'http://someurl.com/something', true);
xmlhttp.setRequestHeader("Content-Type", "multipart/form-data");
xmlhttp.send(data);

Why is that so? The file exists, data variable is correct. The request is being sent properly. What's wrong?

Use the FormData object for send your file.

var formData = new FormData();
formData.append("file", data); // data is your file
xmlhttp.send(formData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM