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

时间:2018-05-09 07:26:56

标签: node.js base64 buffer google-cloud-storage binary-data

我正在使用第二方api,它以二进制媒体数据格式返回图像。获取此数据后,我想将其上传到Google云端存储。为此,我需要将此数据转换为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);
         }) 

2 个答案:

答案 0 :(得分: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。您需要将OAuth 2.0用于Google云端存储。确保Cloud Storage JSON API也是enabled

答案 1 :(得分:0)

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

相关问题