问题描述
我一直在尝试这个,我没有找到任何好的教程。
我正在尝试使用 Cloud Functions 和 axios 的 Cloud Storage 触发器 onFinalize
发送位于 Google Cloud Storage 中的文件。
问题是将文件附加到 formData
中。
首先,我使用 NodeJS 和 Express 在我自己的后端完成了它,并且它有效。但我也使用了 Multer,但我不知道我是否可以在这里、在 Cloud Storage 触发器中使用 Multer,或者这样做是否有意义。
function to(promise) {
return promise.then(data => {
return [null,data];
})
.catch(err => [err]);
}
exports.onUploadFileDetectAndCreateCorrectAction = functions.storage.object().onFinalize(async (object) => {
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
// Get the file name.
const fileName = path.basename(filePath);
const bucket = admin.storage().bucket(fileBucket);
const tempFilePath = path.join(os.tmpdir(),fileName);
const Metadata = {
contentType: contentType,};
let targetFile = bucket.file(filePath);
let [error,dataDown] = await to(bucket.file(filePath).download({ destination: tempFilePath }));
if (error) throw new Error('Error al descargar archivo al tmpFilePath: ',error);
fs.readFile(tempFilePath,async (error,dataBuffer) => {
if (error) console.log("Error al pedir e lbuffer:",dataBuffer);
log("Data Buffer: ",dataBuffer);
const formData = new FormData();
formData.append("title","2");
formData.append("cover",dataBuffer,'primerImagen');
const response = await axios.post('https://api...',formData,{
headers: {
...formData.getHeaders(),"Content-Type": "multipart/form-data",}
});
})
});
我正在记录 dataBuffer
,我认为这是正确的,因为大小是我上传的图像的大小,但 formData
仍然失败。
我得到的错误是:
错误:请求失败,状态码为 415 在 createError (/workspace/node_modules/axios/lib/core/createError.js:16:15) 在解决 (/workspace/node_modules/axios/lib/core/settle.js:17:12) 在 IncomingMessage.handleStreamEnd (/workspace/node_modules/axios/lib/adapters/http.js:260:11) 在 IncomingMessage.emit (events.js:326:22) 在 IncomingMessage.EventEmitter.emit (domain.js:506:15) 在 endReadableNT (_stream_readable.js:1241:12) 在 processticksAndRejections (internal/process/task_queues.js:84:21)
我尝试了 createReadStream
,这是 CloudStorage 的文件 API 中提到的一种方法。问题在于,当您在 express 中使用 multer 时,来自 CloudStorage 的文件没有称为缓冲区的方法作为文件:
formData.append("cover",bucket.file(filePath).createReadStream(),fileName);
还尝试使用 fs.createReadStream
和 readFile
传递缓冲区:
formData.append("cover",fs.createReadStream(filePath),fileName);
formData.append("cover",fs.readFile(filePath),fileName);
但也不起作用。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)