【发布时间】:2021-10-28 23:49:59
【问题描述】:
我正在努力从云功能上传一张图片 我正在使用 onRequest 将图像从网络发送到云功能。我正在发送一个 base64 字符串和文件名。现在我在互联网上关注不同的教程,似乎无法解决我的问题。
这是我的代码。我认为我在服务帐户 json 上做错了。虽然我生成了 json 文件并使用了它,但它仍然没有工作。
当我不使用服务帐户 json 时,我收到 The caller does not have permission at Gaxios._request 的错误
当我确实使用 serviceAccount.json 时,我会收到此错误 The "path" argument must be of type string. Received an instance of Object,我认为该错误来自 file.createWriteStream()
这里是代码,任何人都可以帮我解决这个问题
我使用的projectId如下图所示
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const projectId = functions.config().apikeys.projectid; // In the picture below
const stream = require("stream");
const cors = require("cors")({ origin: true });
const { Storage } = require("@google-cloud/storage");
// Enable Storage
const storage = new Storage({
projectId: projectId, // I did use serviceAccount json here but that wasn't working
});
// With serviceAccount.json code
// const storage = new Storage({
// projectId: projectId,
// keyFilename: serviceAccount,
// });
// This is giving the error of: The "path" argument must be of type string. Received an instance of Object
exports.storeUserProfileImage = functions.https.onRequest((req, res) => {
cors(req, res, async () => {
try {
const bucket = storage.bucket(`gs://${projectId}.appspot.com`);
let pictureURL;
const image = req.body.image;
const userId = req.body.userId;
const fileName = req.body.fileName;
const mimeType = image.match(
/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/
)[1];
//trim off the part of the payload that is not part of the base64 string
const base64EncodedImageString = image.replace(
/^data:image\/\w+;base64,/,
""
);
const imageBuffer = Buffer.from(base64EncodedImageString, "base64");
const bufferStream = new stream.PassThrough();
bufferStream.end(imageBuffer);
// Define file and fileName
const file = bucket.file("images/" + fileName);
bufferStream
.pipe(
file.createWriteStream({
metadata: {
contentType: mimeType,
},
public: true,
validation: "md5",
})
)
.on("error", function (err) {
console.log("error from image upload", err.message);
})
.on("finish", function () {
// The file upload is complete.
console.log("Image uploaded");
file
.getSignedUrl({
action: "read",
expires: "03-09-2491",
})
.then((signedUrls) => {
// signedUrls[0] contains the file's public URL
console.log("Signed urls", signedUrls[0]);
pictureURL = signedUrls[0];
});
});
console.log("image url", pictureURL);
res.status(200).send(pictureURL);
} catch (e) {
console.log(e);
return { success: false, error: e };
}
});
});
【问题讨论】:
-
请附上您使用服务帐号的代码。
-
@VictorEronmosele 做到了吗
标签: javascript node.js firebase google-cloud-functions google-cloud-storage