gpt4 book ai didi

java - Spring 文件上传 - 'Required request part is not present'

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:38 28 4
gpt4 key购买 nike

我正在尝试向我的 Controller 发送 POST 请求,但无法传递任何类型的任何参数,除非我决定使用 JSON。我的目标是将一个字符串和一个文件传递给我的 Controller ,但我一直收到 Required request part 'xxx' is not present 错误。

@RestController
public class ConfigurationController {
@PostMapping(value = "/config")
public ResponseEntity<?> saveEnvironmentConfig(@RequestParam("file") MultipartFile uploadfile){
return ResponseEntity.ok().body(null);
}
}

我这里不能有文件。同样,如果我尝试:

@RestController
public class ConfigurationController {
@PostMapping(value = "/config")
public ResponseEntity<?> saveEnvironmentConfig(@RequestParam("name") String name){
return ResponseEntity.ok().body(null);
}
}

同样的事情我不能在这里得到名字。

我正在通过 Postman 发送请求,如下面的屏幕截图所示:

Postman Request

Postman Request 2

唯一的标题标签用于授权。我没有任何 Content-Type header ,我尝试添加 multipart/form-data 但没有帮助。

我可以传递字符串参数的唯一方法是添加到 URL。所以遵循 http://localhost:8080/SearchBox/admin/config?name=test 是可行的,但这不是我想要的。我想要 Body 部分中的 String 和 File 参数。

我还通过 CURL 进行了测试:

curl -X POST -H "Authorization:Bearer myToken" -H "Content-Type:Multipart/form-data" http://localhost:8080/SearchBox/admin/config --data 'pwd=pwd'
curl -X POST -H "Authorization:Bearer myToken"http://localhost:8080/SearchBox/admin/config --data 'pwd=pwd'
curl -H "Authorization:Bearer myToken" -F file=@"/g123.conf" http://localhost:8080/SearchBox/admin/config

注意:我已经检查过类似的帖子但没有帮助 This , This , This

最佳答案

我终于解决了这个问题并分享了我的解决方案,以防其他人可能遇到同样的问题。

@RestController
@RequestMapping("/")
public class ConfigurationController {

@Bean
public MultipartConfigElement multipartConfigElement() {
return new MultipartConfigElement("");
}

@Bean
public MultipartResolver multipartResolver() {
org.springframework.web.multipart.commons.CommonsMultipartResolver multipartResolver = new org.springframework.web.multipart.commons.CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000);
return multipartResolver;
}
@PostMapping(value = "/config", consumes = "multipart/form-data")
public ResponseEntity<?> saveEnvironmentConfig(@RequestParam("password") String password, @RequestParam("file") MultipartFile submissions)
throws AdminAuthenticationException, ConfigurationException {
return ResponseEntity.ok().body(null);
}
}

关于java - Spring 文件上传 - 'Required request part is not present',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46563182/

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