上传的Node.js的二进制文件 [英] Uploading binary file on Node.js

查看:610
本文介绍了上传的Node.js的二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Flash来录制和上传音频的节点服务器。 Flash客户端是 jrecorder 的的变化。当用户完成录制音频正在使用POST请求(不是一个形式,因为Flash无法创建文件)与音频的ByteArray作为POST请求(看更多的here )。

I am using Flash to record and upload audio to a node server. The Flash client is a variation of jrecorder. When the user is done recording the audio is uploaded using a POST request (not a form because Flash cannot create files) with the audio ByteArray as the data of the POST request (see more here).

我能够正确地接收使用下面的code节点的土地,但散发出来是错位的,你不能听到任何声音文件。随着中说,该文件的内容可以通过VLC等播放器+ Sox是能够连接code作为一个MP3播放。

I am able to receive the file correctly on Node-land using the code below but the audio that comes out is mangled and you cannot hear anything. With that said, the content of the file can be played by VLC and other players + Sox is able to encode it as an mp3.

下面是用我的code当节点:

Here is my code when using Node:

var express = require('express');
var app = express();

app.use (function(req, res, next) {
    req.rawBody = '';
    req.setEncoding('utf8');

    if(req.method.toLowerCase() == "post")
    {
        req.on('data', function(chunk) { req.rawBody += chunk });
        req.on('end', function() { done(req, res); });
    }

    next();
});

function done(req, res)
{
    fs.writeFile('abc.wav', req.rawBody, 'binary', function(err){
        if (err) throw err;

        // Save file to S3
    }   
}

现在,如果我使用相同的Flash客户端,使POST请求到Rails的服务器,并使用下面的code,该文件是完全保存。

Now if I use the same Flash client and make the POST request to a Rails server and use the code below, the file is saved perfectly.

def record
    file = request.raw_post

    # Save file to S3
end

请注意,我不是一个节点专家,所以如果您有任何关于我应该怎么用,而不是保存块请邮寄code例子中的任何建议。我的主要目的,现在的问题是探索节点更有效地完成(缓冲区,溪流等)

Note that I am not a Node expert so please if you have any suggestions on what should I use instead of saving the chunks please post code examples. My main purpose right now is to get this to a working state before exploring other way of accomplishing more efficiently in Node (buffers, streams, etc)

推荐答案

取出以下行

req.setEncoding('utf8');

你没有收到 UTF8 数据,您收到二进制数据。

您会使用一个缓冲,而不是字符串会更好。

You would be better off using a buffer instead of a string

app.use(function(req, res, next) {
  var data = new Buffer('');
  req.on('data', function(chunk) {
      data = Buffer.concat([data, chunk]);
  });
  req.on('end', function() {
    req.rawBody = data;
    next();
  });
});

这篇关于上传的Node.js的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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