【问题标题】:Send blob data to node using fetch, multer, express使用 fetch、multer、express 将 blob 数据发送到节点
【发布时间】:2017-02-02 07:56:12
【问题描述】:

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

      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);
        });

      }

这是我的快速路线,使用 multer:

  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

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

【问题讨论】:

  • 部分multer var upload = multer({ dest: __dirname + '/../public/uploads/' }); var type = upload.single('upl');
  • 如果您尝试仅发送常规字符串而不是 blobData,您会得到什么吗?console.log(blobData) 告诉您什么。
  • 如果您从浏览器的 Web 开发工具查看获取网络请求,浏览器会发送什么 Content-Type 标头?
  • 改成字符串后仍然输出:{ upl: '' }
  • blobData 是一个对象Blob {size: 6937, type: "audio/wav"} size : 6937 type : "audio/wav" __proto__ : Blob

标签: javascript node.js express fetch multer


【解决方案1】:

我只是能够运行上述示例的最低配置,它对我来说很好。

服务器:

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,如本示例中用于调试目的。

【讨论】:

  • 我尝试了硬编码巨大的blobe,它就像一个魅力!谢谢
猜你喜欢
  • 1970-01-01
  • 2016-09-25
  • 2016-09-14
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多