所以我想做一个上传文件的应用程序。 客户端上传如下所示:
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);
};
};
NodeJS(服务器端)代码如下所示:
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);
});
上传功能:
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);
}
});
基本上:当文件以JSON格式(客户端)上传时,服务器会收到此JSON&的块。将它们连接到一个字符串变量中,然后解析json&从解析的json中获取上传的文件二进制数据。
这里的问题是,当文件上传时,它会发生变异(这里,当图像上传时,它会发生变化)
这是一个例子: image changed after upload
我的问题是,为什么?是发送的二进制数据是变异的,还是服务器端问题(节点js fs.writeFile bug?)
感谢。
答案 0 :(得分:0)
所以,我认为你的Node.js代码存在问题。 尝试将其更改为使用缓冲区:
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
uploader.upload(Buffer.concat(body));
/* use
Buffer.concat(body).toString();
if it is a string */
});