Blob 保存为 [object Object] Nodejs [英] Blob saved as [object Object] Nodejs

查看:76
本文介绍了Blob 保存为 [object Object] Nodejs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 HTML5 从麦克风录制音频,然后将其发送到服务器进行保存.然而,目前保存的文件只包含 [object Object]

I want to record audio from the microphone with HTML5, then send it to the server to be saved. Currently however, the saved file just contains [object Object]

这是我的一些代码片段.

Here are some snippets of my code.

console.log(blob);
$http.post('/api/save_recording', blob)
  .success(function(new_recording) {
    console.log("success");
  })

日志打印:

Blob {type: "audio/wav", size: 237612, slice: function}
success

后端:

exports.saveRecording = function(req, res) {
  console.log(req.body);

  fs.writeFile("temp/test.wav", req.body, function(err) {
    if(err) {
      console.log("err", err);
    } else {
      return res.json({'status': 'success'});
    }
  }) 
}

日志打印:{ type: 'audio/wav', size: 786476 }

你能告诉我为什么这不起作用,以及如何解决它吗?

Can you tell me why this isn't working, and how to fix it?

推荐答案

我终于搞定了.实现此功能的方法是在客户端对 blob 进行编码,然后在服务器上对其进行解码.

I finally got this working. The approach to get this to work is to encode the blob on the client, and decode it on the server.

// converts blob to base64
var blobToBase64 = function(blob, cb) {
  var reader = new FileReader();
  reader.onload = function() {
    var dataUrl = reader.result;
    var base64 = dataUrl.split(',')[1];
    cb(base64);
  };
  reader.readAsDataURL(blob);
};

blobToBase64(blob, function(base64){ // encode
  var update = {'blob': base64};
  $http.post('/api/save_recording', update)
    .success(function(new_recording) {
      console.log("success");
    });
});    

后端:

exports.saveRecording = function(req, res) {
  var buf = new Buffer(req.body.blob, 'base64'); // decode
  fs.writeFile("temp/test.wav", buf, function(err) {
    if(err) {
      console.log("err", err);
    } else {
      return res.json({'status': 'success'});
    }
  }); 
};

这篇关于Blob 保存为 [object Object] Nodejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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