如何用Vanilla Node.js接收blob?

时间:2017-07-24 23:25:09

标签: javascript node.js ajax blob

我有获取请求正文的vanilla代码,但它会创建一个字符串。到目前为止,这对大多数事情都很好,但现在我想收到一个blob。

首先,我现在的代码:

http.createServer(function (request, response) {
  var body = '';

  request.on('data', function (data) {
    //this works great for UTF-8, but does not work for Blobs
    body += data;

    // Too much POST data, kill the connection!
    // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
    if (body.length > 1e7) {
        console.log("POSTED data too large!")
        request.connection.destroy();
    }
  });

  request.on('end', function () {
    var pathname = "test.png";
    fs.writeFileSync(pathname, body, {flag: "w"});

    response.writeHead(200, {
      'Content-Type': 'text/plain',
      "Access-Control-Allow-Origin" : "*"
    });
    response.end("got it")
  });

}).listen(8888);

客户端:

var imgNode; //assume is loaded <img>
var canvas = document.createElement("canvas");
canvas.width = imgNode.naturalWidth;
canvas.height = imgNode.naturalHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgNode, 0, 0);  

canvas.toBlob(function(blob) {
  Ajax.POST("localhost:8888", blob);  //functional Ajax POST
});

这里的问题是此代码仅适用于字符串。什么是适用于Blob的Vanilla代码?

1 个答案:

答案 0 :(得分:1)

使用Buffer代替string应该可以正常工作

http.createServer(function (request, response) {
    var body = Buffer.from([]); // create a buffer

    request.on('data', function (data) {
        // add to buffer
        body = Buffer.concat([body,data]);
        // Too much POST data, kill the connection!
        // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
        if (body.length > 1e7) {
            console.log("POSTED data too large!")
            request.connection.destroy();
        }
    });
    request.on('end', function () {
        var pathname = "test.png";
        fs.writeFileSync(pathname, body, {flag: "w"});

        response.writeHead(200, {
              'Content-Type': 'text/plain',
              'Access-Control-Allow-Origin' : '*',
              // note: I had to add these because of the OPTIONS request
              'Access-Control-Allow-Headers' : 'Content-Type',
              'Access-Control-Allow-Methods' : 'GET,PUT,POST,DELETE,OPTIONS'
        });
        response.end("got it")
    });

}).listen(8888);

当我尝试测试你的代码时,我得到了一个OPTIONS预检 - 上面的代码&#34;处理&#34;它,但它充其量只是hacky - 因为你似乎没有OPTIONS预检(因为你没有在你的代码中处理它)我认为它只是我和#的东西39;你的代码做错了

将数据添加到缓冲区可能是一种更好的方法 - 我暂时没有用节点做过这样的事情

相关问题