所有分类
  • 所有分类
  • 未分类

Knife4j-解决不显示文件上传的问题

简介

本文介绍使用Knife4j时无法上传文件的问题。

问题复现

依赖

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

代码

package com.example.demo.business.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "文件")
@RestController
@RequestMapping("file")
public class FileController {
    @ApiOperation("上传文件")
    @PostMapping("upload")
    public void upload(MultipartFile file) {

    }
}

结果

可以看到,无法上传文件。 

解决方案

在入参上添加注解@RequestPart

package com.example.demo.business.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "文件")
@RestController
@RequestMapping("file")
public class FileController {
    @ApiOperation("上传文件")
    @PostMapping("upload")
    public void upload(@RequestPart MultipartFile file) {

    }
}

结果

备注

网上有人说需要在方法上加@ApiImplicitParam注解,如下:

package com.example.demo.business.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "文件")
@RestController
@RequestMapping("file")
public class FileController {
    @ApiOperation("上传文件")
    @PostMapping("upload")
    @ApiImplicitParam(name = "file", dataTypeClass = MultipartFile.class, paramType = "form")
    public void upload(@RequestPart MultipartFile file) {

    }
}

经我测试,这个不需要加。只在参数上加@RequestPart即可。 ​

3

评论0

请先

显示验证码
没有账号?注册  忘记密码?

社交账号快速登录