<form>
<input id="filesToUpload" type="file" multiple>
<button id="testUpload">Test Upload</button>
</form>
<div id="status"></div>
document.addEventListener('DOMContentLoaded', init, false);
let fileField, statusDiv;
async function init() {
fileField = document.querySelector('#filesToUpload');
statusDiv = document.querySelector('#status');
document.querySelector('#testUpload').addEventListener('click', doUpload, false);
}
async function doUpload(e) {
e.preventDefault();
statusDiv.innerHTML = '';
let totalFilesToUpload = fileField.files.length;
//nothing was selected
if(totalFilesToUpload === 0) {
statusDiv.innerHTML = 'Please select one or more files.';
return;
}
statusDiv.innerHTML = `Uploading ${totalFilesToUpload} files.`;
let uploads = [];
for(let i=0;i<totalFilesToUpload; i++) {
uploads.push(uploadFile(fileField.files[i]));
}
await Promise.all(uploads);
statusDiv.innerHTML = 'All complete.';
fileField.value='';
}
async function uploadFile(f) {
console.log(`Starting with ${f.name}`);
let form = new FormData();
form.append('file', f);
let resp = await fetch('https://httpbin.org/post', { method: 'POST', body:form });
let data = await resp.json();
console.log(`Done with ${f.name}`);
return data;
}
/*
form.append('name', 'ray');
form.append('age', 48);
let resp = await fetch('https://httpbin.org/post', { method: 'POST', body:form });
let data = await resp.json();
console.log(data);
*/
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.