每当用户必须在存储中发布图像时,我不会直接使用 firebase 存储功能,而是使用 onCall 云功能,将 base64 图像传递给它,对其进行修改(5 次),然后将其发布到存储中。
功能如下:
exports.uploadImage = functions.https.onCall(async (data, context) => {
var bucket = admin.storage().bucket();
// Convert the base64 string back to an image
var base64EncodedImageString = data.image,
mimeType = 'image/jpeg',
fileName = 'testName',
imageBuffer = Buffer.from(base64EncodedImageString, 'base64');
if (!fs.existsSync(os.tmpdir()+"/myfolder")){
fs.mkdirSync(os.tmpdir()+"/myfolder");
}
const tempFilePath = path.join(os.tmpdir(),"myfolder", fileName+".jpg");
fs.writeFileSync(tempFilePath,base64EncodedImageString,'base64',function(err){
functions.logger.log("file scritto in"+tempFilePath);
})
await bucket.upload(tempFilePath, {
destination: 'test/'+fileName,
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
const tempFilePath_25 = path.join(os.tmpdir(),"myfolder", fileName+"_25.jpg");
spawnSync('convert', [tempFilePath, '-scale', '10%','-scale','1000%>', tempFilePath_25]);
await bucket.upload(tempFilePath_25, {
destination: 'test/'+fileName+"_25.jpg",
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
fs.unlinkSync(tempFilePath_25);
const tempFilePath_50 = path.join(os.tmpdir(),"myfolder", fileName+"_50.jpg");
spawnSync('convert', [tempFilePath, '-scale', '5%','-scale','2000%>', tempFilePath_50]);
await bucket.upload(tempFilePath_50, {
destination: 'test/'+fileName+"_50.jpg",
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
fs.unlinkSync(tempFilePath_50);
const tempFilePath_75 = path.join(os.tmpdir(),"myfolder", fileName+"_75.jpg");
spawnSync('convert', [tempFilePath, '-scale', '3%','-scale','3333%>', tempFilePath_75]);
await bucket.upload(tempFilePath_75, {
destination: 'test/'+fileName+"_75.jpg",
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
fs.unlinkSync(tempFilePath_75);
const tempFilePath_100 = path.join(os.tmpdir(),"myfolder", fileName+"_100.jpg");
spawnSync('convert', [tempFilePath, '-scale', '1%','-scale','10000%>', tempFilePath_100]);
await bucket.upload(tempFilePath_100, {
destination: 'test/'+fileName+"_100.jpg",
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
fs.unlinkSync(tempFilePath_100);
});
我尝试每 2 秒使用一个 for 循环进行一次模拟,但我得到了 60% 请求的截止日期错误。当我发布应用程序时,会有很多用户(希望如此)可能同时调用相同的函数来发布照片。我怎么解决这个问题?提前致谢。