gpt4 book ai didi

java - Spring Boot 可选的多部分 POST 请求

转载 作者:行者123 更新时间:2023-11-30 06:53:08 24 4
gpt4 key购买 nike

我有一项服务,我希望能够通过 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 并且没有任何文件,我得到 请求被拒绝因为没有找到多部分边界(显然,因为我不'有一个文件)。

这让我想知道如何在我的 Spring 端点中有一个可选的多部分参数?我想避免在我的请求中添加额外的参数,例如“附加文件:真/假”,因为当服务器只能检查是否存在时,这会变得麻烦和不必要。

谢谢!

最佳答案

你的代码没有问题,但是客户端请求的问题,因为如果你想上传图片,Content-Type应该像下面这样,

multipart/form-data; boundary="123123"

尝试删除 Content-Type header 并进行测试,我将举一个服务器代码和客户端请求的示例

服务器代码:

@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);
}

使用 Postman 的客户端请求

带图片 enter image description here

没有图片

enter image description here

curl 示例:

没有图片,有内容类型

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

没有图片,没有内容类型

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

关于java - Spring Boot 可选的多部分 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37886726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com