下面的函数将选定的文件从fileEle
元素发送到后端
const upload = function (fileEle, backendUrl) {
return new Promise(function (resolve, reject) {
// Get the list of selected files
const files = fileEle.files;
// Create a new FormData
const formData = new FormData();
// Loop over the files
[].forEach.call(files, function (file) {
formData.append(fileEle.name, file, file.name);
});
// Create new Ajax request
const req = new XMLHttpRequest();
req.open('POST', backendUrl, true);
// Handle the events
req.onload = function () {
if (req.status >= 200 && req.status < 400) {
resolve(req.responseText);
}
};
req.onerror = function () {
reject();
};
// Send it
req.send(formData);
});
};