csdn产品小助手 2018-06-14 15:43 采纳率: 0%
浏览 27

NodeJS突变了ajax?

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.

  • 写回答

1条回答 默认 最新

  • weixin_33747129 2018-06-14 16:03
    关注

    So, i think the problem in your Node.js code. Try to change it to use Buffer:

    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 */
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配