I am trying to develop a webpage which posts the attached file(s) and other fields on the form. In summary, my page should have the following features:
I researched on the Internet and found this useful article File API with HTML5 about File API and I managed to make it work. All selected files are uploaded to the server. But I want to improve it a little bit.
I don't want to upload them instantly to the server. I want the user to view before they submit and upload only when they click on 'Upload all files now'.
The problem is that I don't know how to loop all the selected files when the user clicks on 'Upload all files now' button. I couldn't manage to re-access all the files which are already selected by the user.
In the example, all files come from evt.dataTransfer.files. But it's undefined when I click the button. Since my code is almost exactly same to codes in the Example, I will post only the important part.
dropArea.addEventListener("drop", function (evt) {
traverseFiles(evt.dataTransfer.files);
this.className = "";
evt.preventDefault();
evt.stopPropagation();
}, false);
$('#btnUploadAll').click(function (evt) {
for (x in evt.dataTransfer.files) {
var file = filesToUpload[x];
//do the upload script to server.
//xxxxxxxxxxxxxxxxxxxx
}
});
My question is how I could get access to the pre-selected files when the user clicks on the 'Upload all files now' button?
The second event is a click event, it just contains all about the click, it will NOT contain anything about files which is contained in the first event.
So what you probably should do is: create a shared variable, in the 1st event set it, and in the second event read it. like the below code shows:
var filesInQueue = []; // shared variable
dropArea.addEventListener("drop", function (evt) {
traverseFiles(evt.dataTransfer.files);
filesInQueue = filesInQueue.concat(Array.from(evt.dataTransfer.files)); // set to the shared variable
this.className = "";
evt.preventDefault();
evt.stopPropagation();
}, false);
$('#btnUploadAll').click(function (evt) {
for (x in filesInQueue) { // read from shared variable
var file = filesToUpload[x];
//do the upload script to server.
//xxxxxxxxxxxxxxxxxxxx
}
});