Fidan Hakaj
Fidan Hakaj

Reputation: 7163

Edit uploaded file client side with javascript

I am developing a web application where the user have to upload a file. Before sending it to server, I will need to modify that file on client side.

Here is the code for loading the file :

var reader = new FileReader();
reader.onload = function(file) {
    var arrayBuffer = reader.result;
    byteArray = new Uint8Array(arrayBuffer);
    //modify byteArray
    //replace the file data with the modified byteArray
}
reader.readAsArrayBuffer(file);

Is it possible to replace the file data with the modified byteArray ?

Upvotes: 3

Views: 3788

Answers (1)

Ben Jackson
Ben Jackson

Reputation: 11922

You can't change the File object, as that represents a file on the user's local filesystem. However, you can create a new Blob from your modified array buffer:

var uploadBlob = new Blob(arrayBuffer);

Then simply upload this uploadBlob in place of the original File object using FormData:

var uploadData = new FormData(),
    request = null;

upload.append('fileData', uploadBlob);

request = new XMLHttpRequest();
request.open("POST", "http://yourURL.com");
request.send(formData);

(Obviously, remember to add any needed handlers to deal with your request's response.)

The only issue is browser support (basically, IE10+):

http://caniuse.com/#feat=xhr2

http://caniuse.com/#feat=blobbuilder

Upvotes: 2

Related Questions