简体   繁体   中英

How to upload file to mongodb on mongoose using nestJS?

Hello pls do somebody know how to upload file to MongoDB (mongoose) using nestJS??

I already have the ability to @Post upload file to my nestJS projet and @Get, but know I wanna post to mongodb using mongoose, pls help

I don't recommend to store images on your database but you can do this:

 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') }

First you have to convert that file to a string with base64 encoding then you can save that string on your database with the create method or updating a document.

If you want to get that file just search that info in your database and then convert the string to buffer and return it.

Like I said before, I don't recommend this it is better if you upload the buffer to s3 and save the link on your database.

thanks it is worked, but it is only buffer a can't see the image? please is there any others option to get is as image: please here what i'm getting :

{"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 service file

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));}

but my backend Nestjs trow error:

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

TypeError: Cannot read property 'buffer' of undefined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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