2017-07-24 28 views
-1

我有香草代碼來獲取請求的主體,但它創建一個字符串。到目前爲止,這對大多數事情都很好,但現在我想要得到一個blob。如何使用Vanilla Node.js接收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代碼?

+0

此代碼僅適用於字符串 - 當您嘗試使用斑點時會發生什麼?哪一方失敗? –

+0

它使一個字符串,而不是一個blob對象。 –

+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預檢(因爲你沒有在你的代碼中處理它),我認爲這只是我的錯誤代碼

可能有更好的方法來添加數據到緩衝區 - 我還沒有做過像這樣的節點在一段時間

+0

對於這個項目,我正在處理野外放棄的預檢和一般CORS。至於緩衝區,謝謝! –

+0

這段代碼很好用。我認爲唯一值得改變的是緩衝區的實例化。 '新的Buffer()'已經被棄用,取代了'Buffer.from([])'https://nodejs.org/api/buffer.html#buffer_new_buffer_array –

+0

改變了代碼,我不知道它已被棄用: p –