【问题标题】:How can I get byte array on nodejs and convert it to a file如何在节点 js 中获取字节数组并将其转换为文件
【发布时间】:2016-08-02 10:04:30
【问题描述】:

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

【问题讨论】:

  • 您能提供更多信息吗?您是否将字节数组发布到 api?您目前采用什么方法?
  • 嘿,我将它发布到 api 是的。我想知道我是否可以 req.body.bytearray 然后 fs.createwritestream(bitearray)

标签: node.js express fs


【解决方案1】:

在你的安卓应用中你会做这样的事情

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
}

在节点方面,我假设您使用的是 express。你可以这样做

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”替换为正确的属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2018-11-07
    • 2014-08-08
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 2014-08-15
    相关资源
    最近更新 更多