如何在nodejs中将二进制字符串写入文件?

时间:2016-02-25 10:40:03

标签: node.js binary filestream

我有一个http请求如下(python代码):

data = open("/tmp/ibus.tar.gz", 'rb').read()
resp = requests.post(url="http://192.168.1.156:3000/upload", data=data, headers={'Content-Type': 'application/octet-stream'})
print resp.text

现在我使用nodejs实施此请求,如下所示:

router.post('/', function(req, res, next) {
  var b = req.body.file;
  fs.writeFile("/tmp/upload.tgz", b, "binary", function(err) {
    if (err) return console.log(err);
    console.log("file is saved");
    return res.send({"status": 200});
  })
});

但我使用/tmp/upload.tgz测试了tar zxf /tmp/upload.tgz,得到的错误如下:

tar: Unrecognized archive format
tar: Error exit delayed from previous errors.

1 个答案:

答案 0 :(得分:0)

req.body.file is undefined因为express不处理文件上传。您必须使用另一个包来处理上载。您也以错误的方式使用请求:

# use an object
data = { 'test': open(path + "test.gz", 'rb') }
# use files as identifier, not data
resp = requests.post("http://localhost:3000/upload", files = data)
print resp.text

例如,使用multer

var fs = require('fs');
var multer = require('multer');
// specify a folder to put the temporary files
var upload = multer({ dest: __dirname + '/uploads' });

// 'test' is the identifier used in the python side, it's not random
router.post('/upload', upload.single('test'), function (req, res, next) {
    var file = req.file;
    console.log(file);

    // at this point, the file is inside the tmp folder, now you can:

    // make a copy
    var src = fs.createReadStream(file.path);
    var dest = fs.createWriteStream(__dirname + '/upload.gz');
    src.pipe(dest);

    // or move it
    fs.renameSync(file.path, __dirname + '/upload.gz');

    res.send('ok');
});