首页 > 解决方案 > 在 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);
         }) 

标签: node.jsbase64buffergoogle-cloud-storagebinary-data

解决方案


您的发布请求应遵循文档中描述的模板。我的帖子请求如下所示:

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 。


推荐阅读