问题
I've started playing around with the excellent http://blueimp.github.io/jQuery-File-Upload/ file upload project.
From the File Processing Options section of the documentation it seems that jquery.fileupload-process.js will let me parse and even modify the file's binary data (files array - with the result of the process applied and originalFiles with the original uploaded files)
(to parse, or append to it or encrypt it or to do something to it)
but for the life of me I can't seem to figure out where is the actual file data within the array so that I can pre-process it before it uploads.
What part of the data array has the "something.pdf" binary file in it? so that I can parse and transform it before upload?
//FROM: jquery.fileupload-process.js
//The list of processing actions:
processQueue: [
{
action: 'log'
}
],
add: function (e, data) {
var $this = $(this);
data.process(function () {
return $this.fileupload('process', data);
});
originalAdd.call(this, e, data);
}
},
processActions: {
log: function (data, options) {
console.log(data.files[0]); //Is it here?
console.log(data); //Is it here?
console.log(data.files[data.index]); //Is it here?
console.log(data.files[data.index].name); //Is it here?
//where?
Thank you.
回答1:
The correct way to access the currently processed file is the following:
var file = data.files[data.index];
For browsers which support the File API, this is a File object.
To retrieve the actual File data, we have to use the FileReader interface:
var fileReader = new FileReader();
fileReader.onload = function (event) {
var buffer = event.target.result;
// TODO: Do something with the ArrayBuffer containing the file's data
};
fileReader.readAsArrayBuffer(file);
回答2:
It may be useful, building on @Sebastian's answer, to explain where to put the FileReader, to work with the fileupload plugin. (I would have made this a comment on @Sebastian's answer, but didn't have space in the comment field).
I have built this in to the process action (using readAsText
instead of readAsArrayBuffer
) as follows:
alertText: function(data, options) {
var dfd = $.Deferred(),
file = data.files[data.index];
var fileReader = new FileReader();
fileReader.onload = function (event) {
var fileText = event.target.result;
alert('Text of uploaded file: '+ fileText);
};
fileReader.readAsText(file);
return dfd.promise();
}
来源:https://stackoverflow.com/questions/20897896/jquery-file-upload-where-is-the-file-data-when-pre-processing-http-blueimp-gi