How to: Upload Files with JavaScript FileAPI - 3 of 3

We have out data seperated in chunks now. Now we have to write a script to send this data to the PHP-script or servlet to save it in a file. This is the elementary part of the the javascript-function and also the simple part. Because we append every chunk to the final file, we can’t work with asynchron requests. If you want to, you have to send also the number of the chunk, and also the final filesize to create a dummy-file and replace the part of the sent chunk. For the javascript the changes are no this big, but the server-side script become more complex.

So.. we will use the synchrone style and work with a simple for-loop to run through our array with the data chunks.


var result=null;
for(var i=0;i<chunks.length;i++){
var last=false;
if(i==(chunks.length-1)){
last=true;
}
result=uploadFileChunk(chunks,filenamePrefix+file.name,url,params,last);
}
return result;


Only the result of the request of the last chunk is returned. Because it is the chunk where the magic (copy from temp-folder to real target folder and create and save entity to database, etc) happens.

I send add a prefix to the filename to create a filename like userid+prefix+filename+fileextension (like *.part or somethin like this). So a user can upload more than one file with the same filename, without cause problems on server side.

But you should also send the original filename as something like "clearname". In this example you can add it to die params-array (params["clearname"]=file.name;) and use it as filename in the db-entity to set this name in header-data on download of this file or in lists of the uploaded files.


function uploadFileChunk(chunk,filename,url,params,lastChunk) {
var formData = new FormData();
formData.append('upfile', chunk, filename);
formData.append("filename",filename);

for(key in params){
formData.append(key,params[key]);
}

if(lastChunk){
formData.append("lastChunk","true");
}
else{
formData.append("lastChunk","false");
}

var xhr = new XMLHttpRequest();

xhr.open("POST", url,false); //false=synchron;
xhr.send(formData);
console.log("upload response-text: "+xhr.responseText);
return xhr.responseText;
}


This is the code where the upload is peformed. It is a FormData-Object (like a form in HTML) and is send via a synchron AJAX-Request.
User annonyme 2015-12-25 21:21

write comment:
Three + = 12

Möchtest Du AdSense-Werbung erlauben und mir damit helfen die laufenden Kosten des Blogs tragen zu können?