springboot整合swagger测试上传文件失效

springboot整合swagger测试上传文件失效

说明:

正常我们使用swagger,正常接口crud操作都是可以的,但是特殊的请求,比如header里面加token,上传文件等可能不支持,我们就需要使用postman,当然了,能使用swagger我们还是使用swagger,因为swagger方便

出现失效情况情景再现

@Controller
@Api(tags = "base64转图片")
@RequestMapping("Base64Controller")
public class Base64Controller {
    @PostMapping("/testbase64")//get请求
//         @ResponseBody
    @ApiOperation(value = "上传图片并回显图片", notes = "", httpMethod = "")
    public String uploadAndShow(HttpServletRequest request, MultipartFile fileupload, Model model) throws IOException {
        byte[] fileByte = fileupload.getBytes();
        if(fileByte.length==0){
            throw new RuntimeException("文件为空,请重新选择文件");
        }
        BASE64Encoder encoder = new BASE64Encoder();
//        File file = new File("G:\\图书馆.jpg");
//        byte[] fileByte = Files.readAllBytes(file.toPath());
        String baseStr = encoder.encode(fileByte);
        String imgStr = "data:image/jpeg;base64," + baseStr;
        model.addAttribute("base", imgStr);
        return "base";
    }
}

image-20210525221053671

解决方法

在MultipartFile加上@RequestPart注解即可

正确方式


@Controller
@Api(tags = "base64转图片")
@RequestMapping("Base64Controller")
public class Base64Controller {
    @PostMapping("/testbase64")//get请求
//         @ResponseBody
    @ApiOperation(value = "上传图片并回显图片", notes = "", httpMethod = "")
    public String uploadAndShow(HttpServletRequest request, @RequestPart MultipartFile fileupload, Model model) throws IOException {
        byte[] fileByte = fileupload.getBytes();
        if(fileByte.length==0){
            throw new RuntimeException("文件为空,请重新选择文件");
        }
        BASE64Encoder encoder = new BASE64Encoder();
//        File file = new File("G:\\图书馆.jpg");
//        byte[] fileByte = Files.readAllBytes(file.toPath());
        String baseStr = encoder.encode(fileByte);
        String imgStr = "data:image/jpeg;base64," + baseStr;
        model.addAttribute("base", imgStr);
        return "base";
    }

image-20210525221457301

@RequestParam和@RequestPart的区别

参考网址:

https://blog.csdn.net/u012894692/article/details/115875674?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162195196216780271545090%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=162195196216780271545090&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allbaidu_landing_v2~default-1-115875674.first_rank_v2_pc_rank_v29&utm_term=%40RequestPart+%E4%BD%9C%E7%94%A8&spm=1018.2226.3001.4187

总结

term=%40RequestPart+%E4%BD%9C%E7%94%A8&spm=1018.2226.3001.4187

总结

当请求头中指定Content-Type:multipart/form-data时,@RequestPart注解可以用对象来接收

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值