I need to upload a part of a file (only the first MB). I’ve created a PHP script which uploads the whole file. The data (formData Object) is passed by a ajax call.
My idea would be now to split the file with javascript (jquery). Is there any solution for my request?
Current code:
function start(a){
//var fSize = $('#fileUpload')[0].files[0].size / 1024;
var formData = new FormData();
formData.append( 'fileUpload', $('#fileUpload')[0].files[0] );
//AJAX
$.ajax({
url: 'script.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(msg){
alert("Win: " + msg);
},
error: function(bla, msg){
alert("Fail: " + msg);
}
});
}
Since you’re using
FormData, which is a fairly new technology, I’ll show you something with new technologies as well.First, read the file with a
FileReaderobject:Then you can create a
Blobfor each splitted part (1e6bytes long each):Finally, you can add all your
Blobs to yourFormDataobject:You should be ok. I haven’t tested it, though.
I don’t know anything about the performance either. You can use
fr.readAsBinaryStringtoo, thus makinge.target.resulta string. This way, you can create theBlobs using a simplesubstring/slice/substr/whatever, but I fear there could be some problems with Unicode characters and whatnot. Plus, maybe it’s slower.Putting everything in a more coherent snippet:
Note:
FormData.appendtakes a third optional parameter, which should be the name of the file in case ofFileorBlobvalues. If not specified,Blobs may get unpredictable random file names.Probably that parameter isn’t standard, and it’s not mentioned in the MDN artice, but I used it in the snippet above nonetheless. Anyway, if you know what you’re doing, you can have several options to specify the file name. For example, with
formData.append("filename", file.name)or sending a custom header in the request.