Nestjs:即使正文验证失败,也要上传图片 [英] Nestjs: Image uploaded even if body validation fails

查看:89
本文介绍了Nestjs:即使正文验证失败,也要上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我对我的英语水平很低表示歉意.

First of all, I apologize for my weak English.

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

I have a method that accepts PUT request, and it receives a file and BlogModel. When I submit the form from frontend and the BlogModel's validation is failed the file is still uploaded.

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();

addBlog方法


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

add-blog.model.ts

add-blog.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;
}

index.hbs

index.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>

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

I expect the file is not uploaded if the validation is failed.

推荐答案

此处发生的事情与NestJS请求周期的执行顺序有关,即,在管道之前如何调用和触发拦截器.在这种情况下,您将调用文件上传拦截器,让该代码根据需要运行,然后验证您的有效负载,因此即使您有无效的有效负载,您仍在上传文件.您可以查看文件上传拦截器,然后查看该代码的外观.如果绝对需要文件上传和有效负载在同一请求中,则可以始终创建自己的验证拦截器而不是管道,并在文件上传拦截器之前运行此验证.否则,您可以向他们提出两个单独的请求.

What's happening here has to do with the Execution order of the NestJS Request Cycle, namely, how interceptors are called and fired before pipes are. In this case, you are calling the file upload interceptor, letting that code run as needed, and then validating your payload, so even if you have an invalid payload you are still uploading the file. You can view the file upload interceptor here and see what that code looks like. If you absolutely need the file upload and payload to be in the same request, you could always create your own validation interceptor instead of pipe and run this validation before the file upload interceptor. Otherwise you can make them two separate requests.

这篇关于Nestjs:即使正文验证失败,也要上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆