javascript - 如何使用 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();
解决方案
我个人的建议是使用 Node.JS 的内置http
或https
包。
为什么?因为您想编写和读取可能大到足以给您带来问题的二进制文件,而至于我测试过的内容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();
更多信息:
推荐阅读
- c# - 如何在 xamarin.forms 中一次显示多个权限?
- docker - 尝试连接到 grpc 服务,在隔离的 Docker 群上运行,通过 Traefik 暴露
- python - 意外行为numpy数组索引
- laravel - Laravel 混合,提取不减少 app.js
- python - 类中的框架出现一秒钟
- visual-studio-code - 如何在扩展命令中修改 vs code 命令
- regex - 使用正则表达式高效搜索 IP 地址
- sql - How to check if column has value if another column is populated in SQL Server?
- shell - 在理解 AWK 脚本逻辑方面需要帮助
- android - 在 Oreo 上 endCall 需要 MODIFY_PHONE_STATE 权限