使用Firebase功能将图像上传到Cloud Storage错误

时间:2019-01-30 13:41:10

标签: javascript firebase google-cloud-storage google-cloud-functions firebase-storage

我正在尝试将base64 jpeg图像上传到Firebase存储,我不知道怎么了。我认为错误不是来自我的图像编码。 我正在尝试使用React Native(获取API)将用户手机中的图片上传到Firebase存储中以发送请求。

index.js文件:

const functions = require("firebase-functions");
const cors = require("cors")({ origin: true });
const fs = require("fs");
const UUID = require("uuid-v4");

const gcconfig = {
projectId: "awsome-34343434343434",
keyFileName: "awsome.json"
};

 const { Storage } = require("@google-cloud/storage");
const storage = new Storage(gcconfig);

exports.storeImage = functions.https.onRequest((request, response) => {
cors(request, response, () => {
console.log("THE BODY:" + JSON.stringify(request.body));

const body = JSON.parse(request.body);
console.log("THE IMAGE:" + body.image);
fs.writeFileSync("/tmp/uploaded-image.jpg", body.image, "base64", err => {
  console.log(err);
  return response.status(500).json({ error: err });
});
const bucket = storage.bucket("awsome-1548769019561");
const uuid = UUID();
console.log("UUID: " + uuid);
bucket.upload(
  "/tmp/uploaded-image.jpg",
  {
    uploadType: "media",
    destination: "/places/" + uuid + ".jpg",
    metadata: {
      metadata: {
        contentType: "image/jpeg",
        firebaseStorageDownloadTokens: uuid
      }
    }
  },
  (err, file) => {
    if (!err) {
      response.status(201).json({
        imageUrl:
          "https://firebasestorage.googleapis.com/v0/b/" +
          bucket.name +
          "/o/" +
          encodeURIComponent(file.name) +
          "?alt=media&token=" +
          uuid
      });
    } else {
      console.log(err);
      response.status(500).json({ error: err });
    }
    }
  );
});
});

我发送的请求正文:

{"image": "/9j/4QG1RXhpZgAATU0AKgAAAAgABwEQA..."}

我收到此错误:

SyntaxError: Unexpected token o in JSON at position 1
at Object.parse (native)
at cors (/user_code/index.js:21:24)
at cors (/user_code/node_modules/cors/lib/index.js:188:7)
at /user_code/node_modules/cors/lib/index.js:224:17
at originCallback (/user_code/node_modules/cors/lib/index.js:214:15)
at /user_code/node_modules/cors/lib/index.js:219:13
at optionsCallback (/user_code/node_modules/cors/lib/index.js:199:9)
at corsMiddleware (/user_code/node_modules/cors/lib/index.js:204:7)
at exports.storeImage.functions.https.onRequest (/user_code/index.js:18:3)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)

1 个答案:

答案 0 :(得分:1)

您的错误是由const body = JSON.parse(request.body);行引起的

Firebase会自动分析请求正文中的数据,您无需自己尝试进行操作,请参见function calls docs中的“ 从请求中读取值”部分。由于您的身体已经是JSON格式,并且您的函数正在尝试对其重新进行JSON修饰...因此它将触发该错误。删除该行,您就不应再收到该错误。