nest js 上傳文件

最近在研究 nestjs,關(guān)于 nestjs 上傳文件比較疑惑,不知道該如何使用,這里介紹下 nestjs 如何上傳文件的。這里將學(xué)會(huì)如下:

1、學(xué)會(huì)上傳一個(gè)文件
2、同時(shí)上傳多個(gè)文件
3、使用自定義的字段
4、上傳文件使用任意的字段名稱,
5、全局配置,比如自定義文件保存的目錄

1、上傳一個(gè)文件

引入依賴

import { Controller, Post, UseInterceptors ,UploadedFile} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';

文件上傳方法

@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file) {
  console.log(file);
}

現(xiàn)在讓我們測(cè)試下,看下收到的 file 是什么樣的??梢允褂?postman,或者其他工具,這里不介紹如何使用工具,如果需要可在評(píng)論區(qū)評(píng)論。如下:

{
  fieldname: 'file',
  originalname: 'ceshi.png',
  encoding: '7bit',
  mimetype: 'image/png',
  buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 07 80 00 00 04 38 08 06 00 00 00 e8 d3 c1 43 00 00 20 00 49 44 41 54 78 9c ec dd 77 9c 94 f5 bd ... 1874657 more bytes>,
  size: 1874707
}

可以看到我們獲得的一個(gè)文件的詳細(xì)信息,以及一個(gè) buffer,我們可以通過收到的 buffer 進(jìn)行存儲(chǔ),如下。

import * as fs from 'fs';

fs.writeFileSync('./hah.jpg', file.buffer);

目前為止我們已經(jīng)學(xué)會(huì)如何上傳一個(gè)文件以及存儲(chǔ)。
上面這種方式,每次都需要自已寫保存文件的方式,可以通過配置,來(lái)定義上傳。
直接在FileInterceptor修改
引入依賴

import { Controller, Post, UseInterceptors ,UploadedFile} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import multer = require('multer');
 @Post('upload')
  @UseInterceptors(FileInterceptor('file', {
    storage: multer.diskStorage({
      destination: (req, file, cb) => {
        cb(null, '/Users/xxxxx/Desktop/aaa');
      },
      filename: (req, file, cb) => {
        cb(null, file.originalname);
      },
    }),
  }))
  async uploade(@UploadedFile() file) {
  
    return file;
  }

當(dāng)然上面的方式也并不是最好了,假如我要寫很多上傳文件,總不能每次都進(jìn)行這么多代碼配置,有沒有一種方式只需配置一次就可以呢,答案是有的,請(qǐng)看下面,5全局配置。

2、同時(shí)上傳多個(gè)文件,

如下,與上面的不同之處有兩個(gè)FilesInterceptor,UploadedFiles
引入依賴

import { Controller, Post, UseInterceptors, UploadedFile, UploadedFiles } from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
 @Post('upload')
  @UseInterceptors(FilesInterceptor('file'))
  uploadFile(@UploadedFiles() file) {
    console.log(file);
  }

日志如下

[
  {
    fieldname: 'file',
    originalname: '1.png',
    encoding: '7bit',
    mimetype: 'image/png',
    buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 07 80 00 00 04 38 08 06 00 00 00 e8 d3 c1 43 00 00 20 00 49 44 41 54 78 9c ec dd 7b ac 6d d9 55 ... 1770419 more bytes>,
    size: 1770469
  },
  {
    fieldname: 'file',
    originalname: '2.png',
    encoding: '7bit',
    mimetype: 'image/png',
    buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 07 80 00 00 04 38 08 06 00 00 00 e8 d3 c1 43 00 00 20 00 49 44 41 54 78 9c ec dd 77 9c 94 f5 bd ... 1874657 more bytes>,
    size: 1874707
  }
]

3、自定義不同的字段名稱鍵

@Post('upload')
@UseInterceptors(FileFieldsInterceptor([
  { name: 'avatar', maxCount: 1 },
  { name: 'background', maxCount: 1 },
]))
uploadFile(@UploadedFiles() files) {
  console.log(files);
}

也可攜帶其他參數(shù)

 @Post('uploads')
    @UseInterceptors(FileFieldsInterceptor([
        { name: 'avatar', maxCount: 1 },
        { name: 'background', maxCount: 1 },
        { name: 'avatar_name'},
        { name: 'background_name'}
    ]))
    async uploads(@UploadedFiles() files,@Body() body) {
        console.log(files,body)
    }

日志如下

[Object: null prototype] {
  avatar: [
    {
      fieldname: 'avatar',
      originalname: '應(yīng)用預(yù)覽圖-1.png',
      encoding: '7bit',
      mimetype: 'image/png',
      buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 07 80 00 00 04 38 08 06 00 00 00 e8 d3 c1 43 00 00 20 00 49 44 41 54 78 9c ec dd 7b ac 6d d9 55 ... 1770419 more bytes>,
      size: 1770469
    }
  ],
  background: [
    {
      fieldname: 'background',
      originalname: '應(yīng)用預(yù)覽圖-3.png',
      encoding: '7bit',
      mimetype: 'image/png',
      buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 07 80 00 00 04 38 08 06 00 00 00 e8 d3 c1 43 00 00 20 00 49 44 41 54 78 9c ec dd 77 9c 94 f5 bd ... 1838100 more bytes>,
      size: 1838150
    }
  ]
} [Object: null prototype] {
  avatar_name: 'ceshi',
  background_name: 'ceshi'
}

斷點(diǎn)截圖:


image.png

4、上傳文件使用任意的字段名稱,

  @Post('upload5')
  @UseInterceptors(AnyFilesInterceptor())
  uploadFileAny(@UploadedFiles() files) {
    console.log(files);
  }

比如定義字段名稱為 aaa


image.png

5、也可以提前注冊(cè),配置好我們文件上傳,下面是如何自定義一個(gè)目錄保存我們的文件。

在Module添加,這種方式更友好,圖片會(huì)存儲(chǔ)在fileUpload目錄下
file.module.ts

import { Module } from '@nestjs/common';
import { FileController } from './file.controller';
import { FileService } from './file.service';
import { MulterModule } from '@nestjs/platform-express';
import dayjs = require('dayjs');
import { diskStorage } from 'multer';
import * as nuid from 'nuid';
@Module({
  imports:[
    MulterModule.register({
      storage: diskStorage({
        //自定義路徑
        destination: `./fileUpload/${dayjs().format('YYYY-MM-DD')}`,
        filename: (req, file, cb) => {
          // 自定義文件名
          // const filename = `${nuid.next()}.${file.mimetype.split('/')[1]}`;
          // return cb(null, filename);
          return  cb(null, file.originalname);
        },
      }),
    }),

  ],
  controllers: [FileController],
  providers: [FileService]
})
export class FileModule {}

file.controller.ts

  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  async UploadedFile(@UploadedFile() file) {
    return file;
  }

寫在最后

如何看到了這里,說明你也喜歡 nestjs,或者對(duì)文件上傳也同樣有疑惑,希望上面的介紹可以幫助你解決問題。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容