Spring 文件上传 - “所需的请求部分不存在”

我正在尝试向我的控制器发送POST请求,但无法传递任何类型的任何参数,除非我决定使用JSON。我的目标是将字符串和文件传递到我的控制器,但我不断收到错误。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

唯一的标头标记用于授权。我没有任何内容类型标题,我试图添加但没有帮助。multipart/form-data

我传递字符串参数的唯一方法是添加到URL。所以以下作品,但这不是我想要的。我想要正文部分中的字符串和文件参数。http://localhost:8080/SearchBox/admin/config?name=test

我还通过 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

注意:我已经检查了类似的帖子,但没有帮助这个这个这个


答案 1

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

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

答案 2
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<?> upload(@RequestParam(value = "name") String 
name,@RequestParam(value = "file") MultipartFile file){
    // TODO check file is not null and save 
    return new ResponseEntity<>(HttpStatus.valueOf(200));;
}

enter image description here