Spring Boot可选的多部分POST请求

时间:2016-06-17 16:58:03

标签: java spring spring-mvc spring-boot

我有一项服务,我希望能够通过POST请求上传文件(包括文件将运行单独的函数)。

我的ReqestMapping看起来像这样的简化版本:

@ApiOperation(value = "Data", nickname = "Create a new data object")
@RequestMapping(value = "/add/{user_id}", produces = "application/json", method = RequestMethod.POST)
public ResponseEntity<Data> addData(@RequestParam("note") String body,
                                            @RequestParam("location") String location,
                                            @RequestParam(value = "file", required = false) List<MultipartFile> file,
                                            @PathVariable String user_id){
    if (file != null) {
        doSomething(file);
    }
    doRegularStuff(body, location, user_id);
    return new ResponseEntity(HttpStatus.OK);
}

可以看出,我的多部分文件列表中有required = false选项。但是,当我尝试curl没有任何文件的端点并且声明我的内容类型为Content-Type: application/json时,我收到的错误是我的请求不是多部分请求。

精细。所以我改为Content-Type: multipart/form-data并且没有任何文件,我得到the request was rejected because no multipart boundary was found(显然,因为我没有文件)。

这让我想知道如何在Spring端点中拥有可选的multipart参数?我想避免在我的请求中添加其他参数,例如“File Attached:True / False”,因为当服务器可以检查是否存在时,这可能变得麻烦且不必要。

谢谢!

1 个答案:

答案 0 :(得分:4)

您的代码没有问题,但客户端请求中存在问题,因为如果您要上传图片,Content-Type应如下所示

multipart/form-data; boundary="123123"

尝试删除Content-Type标头并进行测试,我将为服务器代码和客户端请求添加一个示例

服务器代码:

@RequestMapping(method = RequestMethod.POST, value = "/users/profile")
    public ResponseEntity<?> handleFileUpload(@RequestParam("name") String name,
                                   @RequestParam(name="file", required=false) MultipartFile file) {

        log.info(" name : {}", name);
        if(file!=null)
        {   
            log.info("image : {}", file.getOriginalFilename());
            log.info("image content type : {}", file.getContentType());
        }
        return new ResponseEntity<String>("Uploaded",HttpStatus.OK);
    }

使用邮差的客户请求

带图像的

enter image description here

没有图片

enter image description here

卷曲示例:

没有图片,内容类型

curl -X POST  -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "name=test" "http://localhost:8080/api/users/profile"

没有图片,没有Content-Type

curl -X POST  -F "name=test" "http://localhost:8080/api/users/profile"
相关问题