티스토리 뷰

 프로젝트에서 suneditor를 사용중인데 이미지 업로드를 구현할 일이 생겼다. 그래서 multer를 이용하여 이미지 업로드를 구현했는데 이 부분은 구글에 찾아봐도 잘 안 나와서 혼자 해결해서 누군가도 헤맬 것 같아 여기에 정리해둔다.


MulterModule 설정

@Module ({
    imports: [
        MulterModule. register({
        storage: diskStorage({
            destination: '/public/uploads', // public 하위의 uploads 폴더에 이미지가 저장됨.
            filename: (req, file, callback) => {
                const uniqueSuffix = Date.now() + '-' + Math. round (Math. random) * 1€9);
                const ext = extname (file.originalname) ;
                callback(null, ${uniquesuffix}${ext});
            },
        }),
        }),
    ],
    controllers: [UploadController],
    providers: [UploadService],
})
export class UploadModule {}

에디터 설정

imageUploadUrl: 'http://Localhost:3000/images/upload' // 이미지 업로드 기능이 구현된 엔드포인트 지정

Controller 설정

@Controller()
export class UploadController {
    @Post ('/images/upload')
    @UseInterceptors (FileInterceptor ('file-0'))
    uploadImage(@UploadedFile() file: Express.Multer.File, @Res() response: Response) {
        // 이미지 업로드 응답 결과는 아래와 같은 규격.
        // 다른 규격일 경우 오류 발생.
        const imageInfo = {
        result: [
            {
                name: file.filename,
                size: file.size,
                url: `http://localhost:3000/uploads/${file.filename}`,
            },
        ],
    };
    return response.status(HttpStatus.OK).json(imageInfo); // 무조건 200으로 나가야 한다. 아니면 예외로 잡는다.
}
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함