서문
최근 쇼핑몰 프로젝트 개발에서 nestjs + mongodb 사용의 백엔드, 시스템의 업로드 파일은 확실히 필수적입니다. multer는 공식 권장 업로드 파일 솔루션이지만 공식 문서에 자세히 작성되었지만 실제 전투 또는 일부 함정에 직면 한이 코드 문서에서 신속하게 시작하여 도움을 받기를 바랍니다.
메모리 또는 디스크?
별도의 설정 없이 기본적으로 메모리에 멀티가 저장되는 경우, 업로드된 파일의 데이터 구조는 다음과 같습니다.
js{ fieldname: 'file', originalname: 'unnamed.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 00 c0 00 00 00 c0 08 03 00 00 00 65 02 9c 35 00 00 00 03 73 42 49 54 08 08 08 db e1 4f e0 00 00 ... 10782 more bytes>, size: 10832 }
일반적으로 파일 변환의 논리를 포함하지 않는 것은 이것을 사용하지 않으며 하드 디스크 스토리지는 더 일반적인 요구 사항이어야하며 몇 가지 추가 옵션을 구성해야합니다.
jsimport { MulterModule } from '@nestjs/platform-express'; MulterModule.register({ 'a': './public' });
하드 드라이브 스토리지 업로드 파일 데이터 형식은 다음과 같습니다.
js{ fieldname: 'file', originalname: 'unnamed.png', //원본 파일명 encoding: '7bit', mimetype: 'image/png', destination: './public', //파일이 저장되어 있는 폴더의 위치를 알려주세요. filename: '1704774383763-unnamed.png', //이름을 바꾸지 않기 위해 파일 이름을 업로드 한 후 타임 스탬프를 추가했습니다. path: 'public/1704774383763-unnamed.png', size: 10832 //파일 크기 }
하드 디스크 스토리지 구성
- 글로벌 구성: 프로젝트가 작고 모든 파일을 하나의 폴더에 넣어야 하는 경우, 글로벌이 가장 좋습니다.
jsimport { Module, Global } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { diskStorage } from 'multer'; import { MulterModule } from '@nestjs/platform-express'; // nest아래는 express, 그리고 express와 빌트인 멀티터이므로 설치할 필요 없이 can npm i -D 타입만 설치하시면 됩니다.@types/multer @Global() // 글로벌 수출 @Module({ imports: [ MulterModule.register({ storage: diskStorage({ destination: './public', filename: (req, file, cb) => { return cb(null, `${Date.now()}-${file.originalname}`); }, }), }), ], controllers: [AppController], providers: [], exports: [MulterModule], // 멀티모듈 내보내기 }) export class AppModule {}
글로벌을 사용하면 하위 모듈에서 멀티모듈 모듈을 하나씩 가져올 필요가 없습니다.
모듈 구성 : 하위 모듈 가져 오기 코드는 기본적으로 위와 동일하며 각 모듈이 파일 위치에 저장되는 위치가 일정하지 않으므로 각 모듈을 개별적으로 구성 할 수 있으며 내보내기가 필요하지 않습니다.
인터셉터 구성: 물론 다른 인터페이스가 동일한 모듈의 다른 위치에 저장되는 또 다른 경우가 있으므로 각 인터페이스에 대해 다중 세분화를 정확하게 지정할 수 있습니다.
jsimport { diskStorage } from 'multer'; import { FileInterceptor } from '@nestjs/platform-express'; @UseInterceptors(FileInterceptor('file', { storage: diskStorage({ destination: './another_uploads', filename: (req, file, cb) => { cb(null, `${Date.now()}-${file.originalname}`); }, }), })) uploadFile(@UploadedFile() file) { console.log(file); }
nestjs 정적 파일 서비스
위에서 언급 한 nestjs 업로드 파일 코드를 업로드 한 후 불가피하게 액세스해야하는 nestjs 정적 파일 서비스를 포함하는 첫 번째 설치 패키지도 매우 간단합니다.
jsnpm install --save @nestjs/serve-static
그런 다음 app.module.ts에서 가져오기만 하면 됩니다.
jsimport { Module, Global } from '@nestjs/common'; import { MulterModule } from '@nestjs/platform-express'; import { ServeStaticModule } from '@nestjs/serve-static'; import { diskStorage } from 'multer'; import { join } from 'path'; @Global() @Module({ imports: [ MulterModule.register({ storage: diskStorage({ destination: './public', filename: (req, file, cb) => { return cb(null, `${Date.now()}-${file.originalname}`); }, }), }), ServeStaticModule.forRoot({ rootPath: join(__dirname, '..', 'public'), }), ], controllers: [AppController], providers: [], exports: [MulterModule], }) export class AppModule {}
이렇게 하면 업로드한 파일에 your.domain.com/filename.su... 를 통해 액세스할 수 있습니다.
코딩 전환
jsimport { Module, Global } from '@nestjs/common'; import { MulterModule } from '@nestjs/platform-express'; import { ServeStaticModule } from '@nestjs/serve-static'; import { diskStorage } from 'multer'; import { join } from 'path'; import * as iconv from 'iconv-lite'; @Global() @Module({ imports: [ MulterModule.register({ storage: diskStorage({ destination: './public', filename: (req, file, cb) => { const buffer = Buffer.from(file.originalname, 'binary'); return cb(null, `${Date.now()}-${iconv.decode(buffer, 'utf-8')}`); }, }), }), ServeStaticModule.forRoot({ rootPath: join(__dirname, '..', 'public'), }), ], controllers: [AppController], providers: [], exports: [MulterModule], }) export class AppModule {}
파일 연산에 대한 nodejs는 버퍼로 변환해야 하는데, 여기 예제에서는 Buffer.from () 첫 번째 매개 변수는 원본 파일 이름, 두 번째 매개 변수는 바이너리 단위이며, 여기서는 바이너리이므로 '바이너리'가 됩니다.
백엔드
최근에는 신발 쇼핑몰 풀스택 프로젝트, 모바일 플러터 + 리액트 네이티브, 관리 백엔드 아르코 + 뷰3 + 몽고 + 노드제이스를 할 계획인데 관심 있는 친구들은 팔로우해 주세요.





