Nestjs 图片上传(一)

发布时间:2024年01月17日

1、安装依赖

npm install multer
npm install @types/multer --save-dev

2、生成upload模块

nest g res upload

3、配置图片名称及图片存放路径

upload.module.ts

import { Module } from '@nestjs/common';
import { UploadService } from './upload.service';
import { UploadController } from './upload.controller';
import { MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { join, extname } from 'path';

@Module({
    imports:[
        MulterModule.register({
            storage: diskStorage({
                // 图片存放路径
                destination: join(__dirname, "../images"),
                // 图片文件名
                filename: (_, file, callback) => {
                    const fileName = `${new Date().getTime() + extname(file.originalname)}`;
                    return callback(null, fileName);
                }
            })
        })
    ],
    controllers: [UploadController],
    providers: [UploadService]
})
export class UploadModule { }

4、上传逻辑实现

upload.controller.ts

import { Controller, Get, Post, Body, Patch, Param, Delete, UseInterceptors, UploadedFile } from '@nestjs/common';
import { UploadService } from './upload.service';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('upload')
export class UploadController {
    constructor(private readonly uploadService: UploadService) { }
    
    @Post()
    @UseInterceptors(FileInterceptor('file')) // 'file'为前端表单字段名称
    async uploadFile(@UploadedFile() file) {
        console.log('file', file);
        console.log(`${file.originalname} uploaded successfully.`);
        return `Successfully uploaded ${file.originalname}`;
    }
}

5、配置访问路径

main.ts

import { VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import { NestExpressApplication } from '@nestjs/platform-express/interfaces';
import { join } from 'path';

async function bootstrap() {
    const app = await NestFactory.create<NestExpressApplication>(AppModule);
    app.useStaticAssets(join(__dirname, 'images'),{
        prefix: "/img"
    });
    await app.listen(3000);
}
bootstrap();

6、apifox 上传图片

7、上传成功之后访问图片

?7-1、上传文件存放位置

7-2、访问上传文件
?
文章来源:https://blog.csdn.net/qq_34870529/article/details/135642528
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。