使用fetch,multer,express将blob数据发送到节点

试图发送一个blob对象到我的节点服务器。 在客户端,我使用MediaRecorder录制了一些audio,然后我想将文件发送到我的服务器进行处理。

saveButton.onclick = function(e, audio) { var blobData = localStorage.getItem('recording'); console.log(blobData); var fd = new FormData(); fd.append('upl', blobData, 'blobby.raw'); fetch('/api/test', { method: 'post', body: fd }) .then(function(response) { console.log('done'); return response; }) .catch(function(err){ console.log(err); }); } 

这是我使用Muller的快车路线:

  var upload = multer({ dest: __dirname + '/../public/uploads/' }); var type = upload.single('upl'); app.post('/api/test', type, function (req, res) { console.log(req.body); console.log(req.file); // do stuff with file }); 

但我的日志没有任何回报:

 { upl: '' } undefined 

花了很长时间在这个,所以任何帮助表示赞赏!

       

网上收集的解决方案 "使用fetch,multer,express将blob数据发送到节点"

我只是能够运行上面的例子的最低configuration,它对我来说工作得很好。

服务器:

 var express = require('express'); var multer = require('multer'); var app = express(); app.use(express.static('public')); // for serving the HTML file var upload = multer({ dest: __dirname + '/public/uploads/' }); var type = upload.single('upl'); app.post('/api/test', type, function (req, res) { console.log(req.body); console.log(req.file); // do stuff with file }); app.listen(3000); 

public HTML文件:

 <script> var myBlob = new Blob(["This is my blob content"], {type : "text/plain"}); console.log(myBlob); // here unnecessary - just for testing if it can be read from local storage localStorage.myfile = myBlob; var fd = new FormData(); fd.append('upl', localStorage.myfile, 'blobby.txt'); fetch('/api/test', { method: 'post', body: fd }); </script> 

console.log(myBlob); 在前端打印Blob {size: 23, type: "text/plain"} 。 后端正在打印:

 {} { fieldname: 'upl', originalname: 'blobby.txt', encoding: '7bit', mimetype: 'text/plain', destination: '/var/www/test/public/uploads/', filename: 'dc56f94d7ae90853021ab7d2931ad636', path: '/var/www/test/public/uploads/dc56f94d7ae90853021ab7d2931ad636', size: 23 } 

也可以像本例中一样使用硬编码的Blob来进行debugging。