将二进制媒体数据转换为节点 JS 中的缓冲区



我正在使用第三方api,它以二进制媒体数据格式返回图像。获得这些数据后,我想将其上传到谷歌云存储。为此,我需要将此数据转换为缓冲区。我尝试了多次,但失败了。

我正在使用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);
}
);

看起来您也缺少身份验证。您需要将OAuth 2.0用于Google Cloud Storage。确保也启用了云存储 JSON API。

您需要以流的形式获取文件。这是一篇有用的文章,它指定了如何使用 axios 做到这一点。在服务器中下载文件后,您可以将其作为缓冲区获取,并带有fs.readFile

最新更新