簡體   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