使用获取,合并,表达将Blob数据发送到节点 [英] Send blob data to node using fetch, multer, express

查看:78
本文介绍了使用获取,合并,表达将Blob数据发送到节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to send a blob object to my node server. On the client side I'm recording some audio using MediaRecorder and then I want to send the file to my server for processing.

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

      }

这是我的快速路线,使用了乘积器:

This is my express route, which uses 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
  });

但是我的日志什么也没返回:

But my logs return nothing:

{ upl: '' }
undefined

在此上花了很长时间,所以任何帮助都值得赞赏!

Been spending a long time on this so any help appreciated!

推荐答案

我只能够对您上面的示例进行最小配置,对我来说很好用.

I was just able to run a minimum configuration of your above example and it worked fine for me.

服务器:

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"}.后端正在打印:

The console.log(myBlob); on the frontend is printing Blob {size: 23, type: "text/plain"}. The backend is printing:

{}
{ 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进行尝试,以进行调试.

Maybe also try it with a hard-coded Blob like in this example for debugging purposes.

这篇关于使用获取,合并,表达将Blob数据发送到节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆