问题
I have coded a meteor App, sending slices of binary data to a server with the help of the FileReader API.
The method processing the slices on the client side:
var readSlice = function() {
var start, end;
start = chunk * chunkSize;
if (start > file.size) {
start = end + 1;
}
end = start + (chunkSize - 1) >= file.size ? file.size : start + (chunkSize - 1);
fileReader.onload = function(event) {
if (++chunk <= chunks) {
Meteor
.apply("saveChunk", [ event.target.result.split(',')[1], file.name, clientRegistration, now, (chunk === chunks) ], {
wait : true
});
readSlice();
} else {
/*
* TODO Notify the GUI
*/
console.log("reading done");
}
};
fileReader.readAsDataURL(blobSlice.call(file, start, end));
};
The slices are received by the server in a properly order and are merged in the following fashion:
saveChunk : function(chunk, name, registration, timestamp, last) {
...
tempFile = Meteor.fileTemp + "/" + identifier;
fs.appendFile(tempFile, new Buffer(chunk, "base64"), {
encoding : "base64",
mode : 438,
flag : "w"
}, function(error) {
if (error) {
throw (new Meteor.Error(500, "Failed to save file.", err));
}
});
}
This process works almost fine. However the are minor differences in the file, leading to a corrupted output. The binary differences occur at the point in the file where the output ist splitted, so maybe there is something wrong with the split call on the event.target.result
property, or maybe I am missing something obvious in term of encoding...?
The problem seems to be related to the splitting since a diff of the merged file with the original file shows the following interesting pattern:

回答1:
The corrupted data was result of a simple calculation mistake:
Using
end = (start + chunkSize ) >= file.size ? file.size : (start + chunkSize);
instead of
end = start + (chunkSize - 1) >= file.size ? file.size : start + (chunkSize - 1);
fixed the Problem.
来源:https://stackoverflow.com/questions/19097592/readasdataurl-corrupted-output