node.js - 在 Node JS 中将二进制媒体数据转换为缓冲区
问题描述
我正在使用第三方 api,它以二进制媒体数据格式返回图像。获取此数据后,我想将其上传到 Google Cloud Storage。为此,我需要将此数据转换为 Buffer。我已经尝试了多次,但都失败了。
我正在使用 NodeJS、npm 请求模块调用 api 将图像保存到谷歌云存储。
这是代码:
var binaryData = data;
var bufferData = new Buffer(data);
request({
method: "POST",
url: '/endpoint/upload',
headers: {
'cache-control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
},
formData: {
filename: {
value: fileBase64,
options: {
filename: 'test.jpg',
contentType: 'image/jpeg'
}
},
}
}, function(err, response, body){
console.log(body);
})
解决方案
您的发布请求应遵循文档中描述的模板。我的帖子请求如下所示:
req = https.request({
method: "POST",
protocol: 'https:',
hostname: 'www.googleapis.com',
path: '/upload/storage/v1/b/[bucket-name]/o?uploadType=media&name=[file-name]',
headers: {
'content-type': 'image/png',
'content-length': Buffer.byteLength(data),
'authorizatoin': Bearer [bearer-token]
}
}, (res) => {
console.log(res.statusCode);
console.log(res.statusMessage);
console.log(res.headers);
}
);
看起来您还缺少身份验证。您需要为 Google Cloud Storage 使用 OAuth 2.0。确保也启用了 Cloud Storage JSON API 。
推荐阅读
- whatsapp - whatsapp business api docker images 来自受信任存储库的哈希值
- r - 为什么 R CMD BATCH 不能让你的脚本访问系统的标准输入,而 Rscript 可以?
- java - spring boot如何在k8s中连接localhost mysql?
- simulation - 在 ubuntu 18.04.4 上构建 ns3.29 时出现语法错误
- javascript - jCarousel(连接轮播)与 django
- python - 尝试为兄弟姐妹打印冰棒
- laravel - 获取数据透视表列中不存在的数据 - Laravel 6
- php - PHP 文件权限、chmod 和 mkdir 不起作用
- c++ - openssl .so 库版本不兼容
- php - 如何在 laravel 中同时使用 select 函数和 with 函数