Nestjs:即使正文验证失败也会上传图像

2024-04-06

首先,我为我糟糕的英语表示歉意。

我有一个接受 PUT 请求的方法,它接收一个文件和 BlogModel。当我从前端提交表单并且 BlogModel 的验证失败时,文件仍然会上传。

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './core/app.module';
import { ValidationPipe } from '@nestjs/common';
import { join } from 'path';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.useStaticAssets(join(__dirname, '..', 'src/public'));
  app.setBaseViewsDir(join(__dirname, '..', 'src/views'));

  app.setViewEngine('hbs');
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();

添加博客方法


  @Put()
  @UseInterceptors(FileInterceptor('thumbnail', { storage: BlogStorage }))
  addBlog(@UploadedFile() file, @Body() addBlogModel: AddBlogModel) {
    console.log(file);
  }

添加博客.model.ts

import { IsArray, IsBoolean, IsNotEmpty, IsOptional, IsString, Length } from 'class-validator';
import { Expose } from 'class-transformer';

export class AddBlogModel {
  @IsNotEmpty()
  @IsString()
  title: string;

  @IsString()
  @Length(10, 225)
  @IsOptional()
  introduction: string;

  @IsNotEmpty()
  @IsString()
  content: string;

  @IsBoolean()
  @Expose({name: 'is_published'})
  isPublished: boolean;

  @IsArray()
  @IsNotEmpty()
  tags: string[];

  @IsString()
  @IsNotEmpty()
  category: string;
}

索引.hbs

<!DOCTYPE html>
<html>
<head>

</head>

<body>
<form id="form">
    <input name="title" id="title"/>
    <input name="content" id="content"/>
    <input type="file" name="thumbnail" id="thumbnail"/>

    <button type="submit">Submit</button>
</form>

<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#form").on('submit', function (e) {
            e.preventDefault();
            const data = $(this).serializeArray()
            const data_from_array = {}
            var formData = new FormData()

            $.map(data, function(n, i){
                formData.append(n['name'], n['value'])
            });

            const file = $('input[type="file"]')[0].files[0]

            formData.append('thumbnail', file)

            const config = {
                headers: {
                    'content-type': 'multipart/form-data'
                }
            }
            axios.put('http://localhost:3000/blogs', formData, config).then(res => {
                console.log(res)
            }).catch(err => {
                console.log(err.response)
            })
        });
    })
</script>
</body>
</html>

我希望如果验证失败,文件不会上传。


这里发生的事情与 NestJS 请求周期的执行顺序有关,即如何在管道之前调用和触发拦截器。在这种情况下,您将调用文件上传拦截器,让该代码根据需要运行,然后验证您的有效负载,因此即使您有无效的有效负载,您仍然可以上传文件。你可以在这里查看文件上传拦截器 https://github.com/nestjs/nest/blob/master/packages/platform-express/multer/interceptors/file.interceptor.ts看看代码是什么样子的。如果您绝对需要文件上传和有效负载位于同一请求中,则始终可以创建自己的验证拦截器而不是管道,并在文件上传拦截器之前运行此验证。否则,您可以向他们提出两个单独的请求。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Nestjs:即使正文验证失败也会上传图像 的相关文章

随机推荐