【发布时间】:2020-03-05 04:58:29
【问题描述】:
这是我的代码:-
exports.uploadImage = (req, res) => {
const BusBoy = require('busboy');
const path = require('path');
const os = require('os');
const fs = require('fs');
const busboy = new BusBoy({ headers: req.headers });
let imageFileName;
let imageToBeUploaded = {};
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
const imageExtension = filename.split('.')[filename.split('.').length - 1];
imageFileName = `${Math.round(Math.random() * 100000000000)}.${imageExtension}`;
const filepath = path.join(os.tmpdir(), imageFileName);
imageToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on('finish', () => {
console.log('Busboy on started');
//code breaks here
admin.storage().bucket().upload(imageToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imageToBeUploaded.mimetype
}
}
})
.then(() => {
const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
console.log('logging image url' + imageUrl);
return db.doc(`/users/${req.user.handle}`).update({ imageUrl })
})
.then(() => {
return res.json({ message: 'Image uploaded successfully' });
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: err.code });
})
});
busboy.end(req.rawBody);
}
我在评论中提到了我的代码在哪里中断,我得到的错误是Error: Cannot parse response as JSON: Not Found
message: 'Cannot parse response as JSON: Not Found'
错误消息显示无法将响应解析为JSON。这是否意味着来自 firebase 的响应不是 JSON?我在请求的标头中有一个令牌,在正文中有一个图像作为表单数据。我真的不知道哪里出了问题,请帮忙
【问题讨论】:
-
你有没有试过把它变成一个minimal, complete, reproducible example(例如,一个只查看存储调用的单独的?特别是因为你混合了firebase风格(例如使用管理API)和非 firebase 风格(您的云函数声明),有一些完整的东西可以重现会很有帮助。
-
另一个观察结果——与其将输入文件通过管道传输到文件系统,然后通过
upload()将其读回,不如使用 GCS createWriteStream API 并直接通过管道传输。跨度> -
@robsiemb 实际上我正在关注一个在线教程,代码来自该教程,所以我不知道我遵循什么风格
-
@robsiemb 你能说出你的意思是什么吗?
-
管道:调用
file.pipe()写入流。当您可以直接写入通过createWriteStreamapi 进入 GCS 的流时,没有理由写入文件系统然后从文件系统读回。
标签: firebase google-cloud-firestore google-cloud-functions google-cloud-storage firebase-storage