gpt4 book ai didi

node.js - 无法使用 firebase 函数将字节数组图像上传到 fire-storage

转载 作者:搜寻专家 更新时间:2023-10-31 23:44:27 26 4
gpt4 key购买 nike

我无法使用云函数将字节数组格式的图像文件上传到 firestore。下面的代码在本地使用 app.listen() 工作正常,但是当我尝试使用 exports 函数时它不起作用

const functions = require('firebase-functions');
const { Storage } = require('@google-cloud/storage');
const express = require('express');
var app = express();
var fs = require('fs');

// Your Google Cloud Platform project ID
const projectId ='<project-Id>';

// Creates a client
const storage = new Storage({
projectId: projectId,
keyFilename: '<>'
});


const bucket = storage.bucket("<bucket-name>");

// Byte aray to Image

function saveImage(filename, data) {
console.log("inside saveImage", data.length);
var myBuffer = new Buffer.alloc(data.length);
for (var i = 0; i < data.length; i++) {
myBuffer[i] = data[i];
}
console.log(myBuffer)
fs.createWriteStream(filename, myBuffer, 'binary', function (err) {
console.log("inside writeFile");
if (err) {
console.log('error inside fs', err);
} else {
console.log("The file was saved!");
}
});
}

saveImage("image1.png", result);


app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept");
next();
});



exports.UploadImage = functions.https.onRequest(app);

谁能帮帮我。提前致谢

最佳答案

这是我使用 Firebase FunctionsGoogle Cloud Pub/Sub 将文件上传到 Firebase Storage 时最终得到的解决方案。

NOTE Pub/Sub is optional and only worked for my use case

const functions = require('firebase-functions');
const admin = require('firebase-admin');

function saveImage(filename, data) {
const bucket = admin.storage().bucket();
const imageBuffer = new Uint8Array(data);
const file = bucket.file(`optional_sub_directory/${filename}`, {
uploadType: {resumable: false}
});

file.save(imageBuffer, (err) => {
if (err) {
console.error(`Error uploading: ${filename} with message: ${err.message}`);
return;
}

console.log('Uploaded file');
});
}

exports.helloPubSub = functions.pubsub
.topic('demo-topic')
.onPublish(async(message) => {
/**
* Here goes code to extract the file buffer
*/

const buffer = /** buffer */

saveImage("stack_overflow.txt", buffer);
});

关于node.js - 无法使用 firebase 函数将字节数组图像上传到 fire-storage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54707984/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com