首页 > 解决方案 > 如何使用 put 方法用缓冲区数组写入文件?

问题描述

有没有办法使用缓冲区数组和内容类型和 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();

标签: javascriptnode.jsstreambuffer

解决方案


我个人的建议是使用 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


推荐阅读