简体   繁体   中英

Javascript file upload in 2 steps

I know there are lots of topics explaining the file upload via javascript. But my problem is something else with it.

I have my file upload with plain JS, which works fine but my problem is, I don't want the files get straight uploaded after choosing them from the form. Because the form has got other input field and I want to upload everything to the server after hitting the save button via ajax. I don't want to refresh the page either therefore everything should go through ajax.

Long story short: There are 3 input(text) fields, an input(file) field and a save button in my form. After hitting the save button the form calls a JS function and this has to handle the data(texts and files) and send it via ajax to server.

Hope I could explain the problem.

<form>
<input type="text" name="field1">
<input type="text" name="field2">
<input type="text" name="field3">
<input type="file" name="file" multiple id="myFile" onchange="uploadPicture()">
</form>

And the JS

function uploadPicture() {
var formData = new FormData();
for (var i = 0; i < document.getElementById('myFile').files.length[i]) {
formData.append('files[]', file);
....
and in here I send the formData via ajax to my server, which works fine.

Now my problem is not sending the data straight to the server but saving them temporary and then after hitting the save button sending everything to server...

I wonder if there is a way (trick) to having the files saved between uploading and sending.

Hope it is more clear now.

Thanks

Move the declaration of your formData variable into the outer scope, only add the files in uploadPicture and then use formData in the click-handler on your save button.

I hope that helps.

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