@RequestPart注解的REST API

本文讨论了如何在RESTAPI中使用@RequestPart注解进行文件上传,强调了Content-Type设置和MultipartFile的使用,以及与@RequestParam的区别,后者适用于字符串参数而@RequestPart处理更复杂的数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@RequestPart注解的REST API的做法

问题

为了验证接口, 想使用apipost批量插入多条数据到服务器中, 但是一直没搜索到使用方法.
接口如下:

@ApiOperation("上传文件")
    @PostMapping("/upload-file")
    public TeamResponseMsg uploadFile(@RequestParam(value = "month") String month,
                                      @RequestPart("file") MultipartFile file){
                                      }

解决方案

设置的要点是:

  1. Content-Type需要设置成undefined.

  2. Body中的JsonObject也需要通过文件的方式上传, 并且key的值和API的@RequestPart里的value一致.

这里想强调的是, 大家都知道MultipartFile file参数, 是通过在postman使用file上传的. 但是和file一并通过@RequestPart的Json对象, 也是通过file的方式上传的, 其他方式都不行.

文末附@RequestParam和@RequestPart的区别.

body设置

在这里插入图片描述

header设置

在这里插入图片描述

区别

@RequestPart

    /**
     * 单文件上传
     * @param file
     * @param bucket
     * @return
     */
    @RequestMapping("uploadFile")
    public JsonResult uploadFile(@RequestPart("file") MultipartFile file, @RequestParam String bucket){
 
        String fileUrl = aliossService.uploadFile(file, bucket);
        Map<String,String> result = new HashMap<>();
        result.put("fileUrl",fileUrl);
 
        return success(result);
    }

@RequestParam

    /**
     * 上传字符串
     * @param stringFile
     * @param bucket
     * @return
     */
    @RequestMapping("uploadStringFile")
    public JsonResult uploadStringFile(@RequestParam("stringFile") String stringFile, @RequestParam("bucket") String bucket){
 
        String fileUrl = aliossService.uploadStringFile(stringFile, bucket);
        Map<String,String> result = new HashMap<>();
        result.put("fileUrl",fileUrl);
 
        return success(result);
    }

1.@RequestPart这个注解用在multipart/form-data表单提交请求的方法上。
2.支持的请求方法的方式MultipartFile,属于Spring的MultipartResolver类。这个请求是通过http协议传输的。
3.@RequestParam也同样支持multipart/form-data请求。
4.他们最大的不同是,当请求方法的请求参数类型不再是String类型的时候。
5.@RequestParam适用于name-valueString类型的请求域,@RequestPart适用于复杂的请求域(像JSON,XML)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值