无法使用NodeJS通过Google Photos API上传图像

时间:2019-10-17 17:17:24

标签: javascript node.js google-photos-api

我有内置于NodeJS中的应用程序,它应该使用Google Photos API将图片上传到Google Photos 对于我成功完成的身份验证部分,当我尝试上传图片时出现问题,但我没有问题地收到上传令牌,但是当我尝试使用mediaItems:batchCreate时,它会返回:

"status": {
    "code": 3,
    "message": "Failed: There was an error while trying to create this media item."
  }

这是我将代码转换为base64的代码:

var base64str = fs.readFileSync('1.jpg', 'base64');

这是我收到上传令牌的响应的请求:

request({
method: 'post',
headers: {
'content-type' : 'application/octet-stream',
'Authorization': `Bearer ${userToken}`,
'X-Goog-Upload-File-Name' :  '1.jpg',
'X-Goog-Upload-Protocol' : 'raw'
},
url: `https://photoslibrary.googleapis.com/v1/uploads`,
rejectUnauthorized: false,
body: base64str
}, function(err,response,body) {
      console.log(body);
      });

到目前为止,我没有问题,因为(正文)响应是上传令牌,我收到了。 现在,当我想转到步骤2来请求mediaItems:batchCreate时,代码如下:

let reqObject = {
    newMediaItems: [
      {
        description: "Test Image Uploading",
        simpleMediaItem: {
        uploadToken: body //Body is the upload token received from prev request
        }
      }
    ]
  };
let reqObjectString = JSON.stringify(reqObject);

  request({
    method: 'post',
    headers: {
    'content-type' : 'application/json',
    'Authorization': `Bearer ${userToken}`,
    },
    url: `https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate`,
    rejectUnauthorized: false,
    body: reqObjectString
  }, function(err,response,result) {
      console.log(result);
});

这里的预期结果应该是成功上传媒体,但是我总是得到这个响应:

{
  "newMediaItemResults": [
    {
      "uploadToken": "CAISmQMASsyg4MwSgB2y46/QI2yAAfw/uSeHZaiwGaskaT9J3SEvOtBg4bkOb9Fd0WMhE5OML8aMJMGZWNyC3Di/woTjLGD/VJMtKBk7bg1ZyK5CA+92vk0mjUWVR2LQhhTkEs02aHRr6EkCER3rxk3AqkhC+bxTIViLerUeoKigdlqozrEJXyCLM5U+Eqjdidi0e0hEFeLqs8Yz0V8YpyWQnN+zZUp/+R4pVT9fPXUOyNlsTj5OcMLrtC3Z/W9YnKhQA0O8io8LtmMBJTf04v3YPEtoNvJTd+k5Ux7qWQYJCS60V1R+hPl76jlryos3gnVaaCxHGH/TIMmtwo2zDH+vXTyktMhr82hdMON3Mm2PCfSbJawCLuHSNND9vojO11FEs7LVXAfY1UDDzVXwv4VV8tG9F3tQVI8/4YlkR+KJUjaX6/E4ZFWx67E+swqh16HN1RXXU211eCl36mPxsX35IGPEwvhpZ89LKfk+NU1fVuHB+pNLMNQ+mZOkKs0v6VLcN+nyMpOwjAstg4QUSJdCP+virY1a2uGKwYJh",      
        "status": {
        "code": 3,
        "message": "Failed: There was an error while trying to create this media item."
      }

任何人都可以帮忙,在此先感谢

1 个答案:

答案 0 :(得分:0)

您的评论绝对正确。 google photos API需要媒体为二进制格式,而不是base64格式。

我正在使用React.js和FileReader读取媒体。我必须使用:

const reader = new FileReader()
reader.readAsArrayBuffer()

获取数组缓冲区,然后图像成功上传。