Manipulating and Uploading Form File Data using HTML5 Technology
I'm tying to use the HTML5 FileReader and possibly the FileWriter API to manipulate and then upload the manipulated data from a file type input tag.
Here's what I have so far:
$(function() {
$("#files").change(function(e) 开发者_开发技巧{
var files = e.target.files
, reader = new FileReader()
, i;
for(i=0; f = files[i]; ++i) {
f = doSomething(reader.readAsBinaryString(f)); // Manipulate the File
}
return true;
});
});
So how would I go about implementing the doSomething method? I need to return a FileObject that the form can then submit. Is this currently possible on any of the browsers?
Thank you.
There are a couple of things wrong with your current approach:
You don't need the FileWriter
API. That cannot be used without the HTML5 Filesystem API. What you do need is the BlobBuilder
API from the File API: Writer spec.
Second, the FileReader
read methods are asynchronous, so you can't pass the result
to doSomething()
like you're doing. You also need to create a separate reader object for each file.
One thing you could try is to read the file as an ArrayBuffer
, manipulate its bytes via a JS typed array (Uint8Array
), create a Blob from that buffer, then send the result to the server. Something like this might work (untested):
$(function() {
$("#files").change(function(e) {
var files = e.target.files;
[].forEach.call(files, function(f, i) {
var reader = new FileReader();
reader.onload = function(e) {
doSomething(this.result);
};
reader.readAsArrayBuffer(f);
});
return true;
});
});
var doSomething = function(arrayBuffer) {
// Create a unsigned 8-bit view from the underlying data buffer.
var ui8a = new Uint8Array(arrayBuffer);
for (var i = 0; i < ui8a.length; ++i) {
// Manipulate each byte. Its underlying arraybuffer will be changed.
// ui8a[i] = xxx // set byte at offset i to something.
}
var bb = new WebKitBlobBuilder(); // Build a blob from the arraybuffer data.
bb.append(ui8a.buffer);
upload(bb.getBlob('your/filemimetype'));
};
var upload = function(blob) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server', true);
xhr.onload = function(e) { ... };
xhr.send(blob);
};
I'm not sure if you need the mimetype passed into bb.getBlob()
, but that would
be the content type of the file you're working with. Try it.
精彩评论