繁体   English   中英

如何使用nestJS将文件上传到mongoose上的mongodb?

[英]How to upload file to mongodb on mongoose using nestJS?

您好,请问有人知道如何使用nestJS将文件上传到MongoDB(猫鼬)吗?

我已经能够@Post 上传文件到我的nestJS projet 和@Get,但我知道我想使用 mongoose 发布到 mongodb,请帮助

我不建议将图像存储在您的数据库中,但您可以这样做:

 async function saveFile(file: Express.Multer.File){ //Convert the file to base64 string const fileB64 = file.buffer.toString('base64') //userModel is a mongoose model //Store the string await this.userModel.create({file: fileB64}) } async function getFile(userId: string){ //Get user from database const user = await this.userModel.findOne({_id: userId}).lean() if(.user) throw new NotFoundException('User not found') const file = user.file //Convert the string to buffer return Buffer,from(file, 'base64') }

首先,您必须将该文件转换为具有 base64 编码的字符串,然后您可以使用 create 方法或更新文档将该字符串保存在数据库中。

如果您想获取该文件,只需在数据库中搜索该信息,然后将字符串转换为缓冲区并返回它。

就像我之前说的,我不建议这样做,最好将缓冲区上传到 s3 并将链接保存在数据库中。

谢谢它的工作,但它只是一个看不到图像的缓冲区? 请问还有其他选择吗,如图所示:请在这里我得到什么:

{"type":"Buffer","data":[255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,72,0,72,0,0,255,225,0,120,69,120,105,102,0,0,73,73,42,0,8,0,0,0,4,0,18,1,3,0,1,0,0,0,1,0,0,0,49,1,2,0,7,0,0,0,62,0,0,0,18,2,3,0,2,0,0,0,2,0,2,0,105,135,4,0,1,0,0,0,70,0,0,0,0,0,0,0,71,111,111,103,108,101,0,0,3,0,0,144,7,0,4,0,0,0,48,50,50,48,2,160,4,0,1,0,0,0,208,2,0,0,3,160,4,0,1,0,0,0,0,5,0,0,0,0,0,0,255,192,0,17,8,5,0,2,208,3,1,34,0,2,17,1,3,17,1,255,196,0,31,0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,255,196,0,181,16,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125,1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193....

Angular服务文件

postFile(fileToUpload: File): Observable<any> {

const formaData: FormData = new FormData();
formaData.append('fileKey', fileToUpload, fileToUpload.name);
return this.http.post(`${this.backEndURL}/api/prods/upload/two/tree/`, JSON.stringify(formaData));}

但我的后端 Nestjs 错误:

[ExceptionsHandler] Cannot read property 'buffer' of undefined +80859ms

TypeError:无法读取未定义的属性“缓冲区”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM