如何在nodejs上获取字节数组并将其转换为文件

时间:2016-04-12 01:59:41

标签: node.js express fs

我试图从android获取一个字节数组,然后尝试将其转换为文件。我该怎么做呢?我也在使用快递框架。

1 个答案:

答案 0 :(得分:1)

从你的Android应用程序中你会做这样的事情

String url = "http://yourserver/file-upload";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    // show error
}

在节点方面,我假设你正在使用快递。你可以做这样的事情

var fs = require('fs');
app.post('/file-upload', function(req, res) {
    // get the temporary location of the file
    var tmp_path = req.files.yourfile.path;
    // set where the file should actually exists - in this case it is in the "images" directory
    var target_path = './public/images/' + req.files.yourfile.name;
    // move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err) throw err;
        // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
        fs.unlink(tmp_path, function() {
            if (err) throw err;
            res.send('File uploaded to: ' + target_path + ' - ' + req.files.yourfile.size + ' bytes');
        });
    });
};

执行console.log(req.files)以查看Android应用程序发布的内容。将req.files。 yourfile 中的“yourfile”替换为正确的属性。