So i wanted to do an app that uploads files. The client side upload looks like this:
upload_btn.onclick = function(){
var f = fileinput.files[0];
if (f) {
var r = new FileReader(f);
r.onload = function(e) {
var contents = e.target.result;
if(false)
alert("name: " + f.name + "n"
+"type: " + f.type + "n"
+"size: " + f.size + " bytesn"
+ "starts with: " + contents
);
var json = { fname:f.name, fsize:f.size, binary:contents };
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', progressHandler, false);
request.open("POST", "/upload");
request.setRequestHeader("Content-Type", "application/json");
//request.open("POST", upload_form.action);
request.send( JSON.stringify(json) );
};
r.readAsBinaryString(f);
};
};
And the NodeJS (server side) code looks like this:
http.createServer(function (req, res) {
if (req.method == 'POST') {
var post_data = '';
req.on('data', function (data) {
post_data += data;
});
req.on('end', function () {
uploader.upload(post_data);
});
The Upload function :
fs.writeFile( upload_path+"test.jpg", json.binary, "binary", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
oncomplete();
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(e);
}
});
So basically : when the file is uploaded in a JSON format (client-side), the server receives the chunks of this JSON & join them in a string-variable, then parses the json & get the uploaded file binary data from the parsed json.
the problem here is, when the file is uploaded it is mutated (here, when an image is uploaded, it changes)
here's an example : image changed after upload
My question, is why? is it the sent binary data that is mutated, or is it a server side problem (node js fs.writeFile bug?)
thanks.