【问题标题】:Convert Binary Media Data to Buffer in Node JS在 Node JS 中将二进制媒体数据转换为缓冲区
【发布时间】:2018-05-09 07:26:55
【问题描述】:

我正在使用第三方 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.js base64 buffer google-cloud-storage binary-data


    【解决方案1】:

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

    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);
                    }
             );
    

    您似乎还缺少authentication。您需要为 Google Cloud Storage 使用 OAuth 2.0。确保 Cloud Storage JSON API 也是 enabled

    【讨论】:

      【解决方案2】:

      您需要以流的形式获取文件。这是一个useful post,它指定了如何使用 axios 执行此操作。在服务器中下载文件后,您可以使用fs.readFile 将其作为缓冲区获取。

      【讨论】:

        猜你喜欢
        • 2012-01-26
        • 2018-09-18
        • 1970-01-01
        • 2016-09-16
        • 1970-01-01
        • 2014-02-21
        • 2011-09-20
        • 1970-01-01
        相关资源
        最近更新 更多