【问题标题】:how to write file with buffer array using put method?如何使用 put 方法用缓冲区数组写入文件?
【发布时间】:2019-01-16 07:22:38
【问题描述】:

有没有办法使用缓冲区数组和内容类型和 put 方法写入文件?

requestify.request('some url', {
                    method: 'PUT',
                    body: buffArray, //need modifications here
                    headers: {
                        'Content-Type': res_file.headers['content-type']
                    }
                }).then(function (res) {
                    console.log(res);
                })

我可以发送数据,但文件存储不正确。

工作 Java 代码

   httpcon.setRequestMethod("PUT");
        httpcon.setReadTimeout(100000);
        httpcon.setDoOutput(true);
        httpcon.setRequestProperty("Content-Type", conenttype);
        httpcon.connect();
        OutputStream os = httpcon.getOutputStream();

        os.write(in.toByteArray(), 0, in.size());

        responceCode = httpcon.getResponseCode();

        httpcon.disconnect();

【问题讨论】:

  • 你的服务器如何处理请求?

标签: javascript node.js stream buffer


【解决方案1】:

我个人的建议是使用 Node.JS 的内置 httphttps 包。

为什么?因为您想要编写和读取可能大到足以给您带来问题的二进制文件,而至于我用requestify 测试过的内容,在使用二进制响应时它会给您带来问题(它会将它们字符串化!)。

您可以简单地使用流,这将为您省去很多麻烦。

您可以使用它来测试它,例如:

const fs = require('fs');
const http = require('https');

const req = http.request({
  host: 'raw.githubusercontent.com',
  path: '/smooth-code/svgr/master/resources/svgr-logo.png',
  method: 'GET'
}, res => {
  res.pipe(fs.createWriteStream('test.png'));
});
req.end();

并适应您提供的代码:

const fs = require('fs');
const http = require('https');

const req = http.request({
  host: 'some-host',
  path: '/some/path',
  method: 'PUT',
  headers: {
    'Content-Type': res_file.headers['content-type']
  }
}, res => {
  res.pipe(fs.createWriteStream('your-output-file.blob'));
});
// This part: If comes from HDD or from another request, I would recommend using .pipe also
req.write(buffArray);
req.end();

更多信息:

http包https://nodejs.org/api/http.html

fs 包https://nodejs.org/api/fs.html

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2012-05-14
    • 2018-08-25
    • 2023-03-11
    • 2010-10-07
    相关资源
    最近更新 更多