我如何使用Google云存储作为存储区,以在MERN Stack应用中存储用户/客户端图像?
我正在使用mongoDB,express,react和node开发一个漂亮的样板博客风格的应用程序。它允许用户注册,身份验证,授权用户访问CRUD帖子,发表评论和回复评论(到目前为止)。
我有一个定义明确的架构(使用猫鼬),User
模型具有一个avatar
字段,该字段应该是该用户的个人资料图片的URI。这就是我现在要坚持的:将图像托管集成到Google Cloud Storage上以供用户上传的个人资料图片,然后获取URL并将其保存到user.avatar
。
我已经尝试了很多,但没有结果(尽管那是我坐在屏幕上凝视了几个小时后的凌晨4点)。我确实无法找到可靠的解决方案,我应该提到这是我第一次进行文件上传(我是学生,虽然这不是家庭作业问题)。
老实说,任何帮助都将不胜感激。
编辑:我已经尝试过Google Cloud Storage文档。
回答如下:[https://cloud.google/nodejs/getting-started/using-cloud-storage中有一些不错的信息,在Upload to Cloud Storage
部分中。
function sendUploadToGCS (req, res, next) {
if (!req.file) {
return next();
}
const gcsname = Date.now() + req.file.originalname;
const file = bucket.file(gcsname);
const stream = file.createWriteStream({
metadata: {
contentType: req.file.mimetype
},
resumable: false
});
stream.on('error', (err) => {
req.file.cloudStorageError = err;
next(err);
});
stream.on('finish', () => {
req.file.cloudStorageObject = gcsname;
file.makePublic().then(() => {
req.file.cloudStoragePublicUrl = getPublicUrl(gcsname); // this will be the URL you will use in your web pages
next();
});
});
stream.end(req.file.buffer);
}
示例还使用Multer,它是Express的中间件,用于处理文件上传
我如何使用Google云存储作为存储区,以在MERN Stack应用中存储用户/客户端图像?
我正在使用mongoDB,express,react和node开发一个漂亮的样板博客风格的应用程序。它允许用户注册,身份验证,授权用户访问CRUD帖子,发表评论和回复评论(到目前为止)。
我有一个定义明确的架构(使用猫鼬),User
模型具有一个avatar
字段,该字段应该是该用户的个人资料图片的URI。这就是我现在要坚持的:将图像托管集成到Google Cloud Storage上以供用户上传的个人资料图片,然后获取URL并将其保存到user.avatar
。
我已经尝试了很多,但没有结果(尽管那是我坐在屏幕上凝视了几个小时后的凌晨4点)。我确实无法找到可靠的解决方案,我应该提到这是我第一次进行文件上传(我是学生,虽然这不是家庭作业问题)。
老实说,任何帮助都将不胜感激。
编辑:我已经尝试过Google Cloud Storage文档。
回答如下:[https://cloud.google/nodejs/getting-started/using-cloud-storage中有一些不错的信息,在Upload to Cloud Storage
部分中。
function sendUploadToGCS (req, res, next) {
if (!req.file) {
return next();
}
const gcsname = Date.now() + req.file.originalname;
const file = bucket.file(gcsname);
const stream = file.createWriteStream({
metadata: {
contentType: req.file.mimetype
},
resumable: false
});
stream.on('error', (err) => {
req.file.cloudStorageError = err;
next(err);
});
stream.on('finish', () => {
req.file.cloudStorageObject = gcsname;
file.makePublic().then(() => {
req.file.cloudStoragePublicUrl = getPublicUrl(gcsname); // this will be the URL you will use in your web pages
next();
});
});
stream.end(req.file.buffer);
}
示例还使用Multer,它是Express的中间件,用于处理文件上传