spring-boot REST POST API 发送文件

spring-boot REST POST API to send a file

我是 spring 休息的新手,正在尝试创建一个 REST POST API,用户可以在其中向服务器发送文件。

@RequestMapping(value = "/order", method = RequestMethod.POST)
public String create(@RequestParam("file") MultipartFile file) {        
        System.out.println("---------INSIDE ORDER----------");
        return "file succesfully received!";
}

但是当我通过上传 order.txt 文件并选择表单数据(在邮递员中)来调用此 API 时,我得到了这个错误

{
  "timestamp": 1474129488458,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.multipart.support.MissingServletRequestPartException",
  "message": "Required request part 'file' is not present",
  "path": "/order"
}

问题不在于您接受请求的代码。跟你的要求一样。

-d用于传递数据。您必须使用 -F 如下所示

curl -X POST localhost:8080/order -F "file=@cooltext.txt"

有关详细信息,请参阅 curl manual 的 post 部分

验证您是否有这些物品:

@Bean
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver multipart = new CommonsMultipartResolver();
    multipart.setMaxUploadSize(3 * 1024 * 1024);
    return multipart;
}

@Bean
@Order(0)
public MultipartFilter multipartFilter() {
    MultipartFilter multipartFilter = new MultipartFilter();
    multipartFilter.setMultipartResolverBeanName("multipartResolver");
    return multipartFilter;
}

并且在 pplications.properties

# MULTIPART (MultipartProperties)
spring.http.multipart.enabled=true 
# Enable support of multi-part uploads.
# spring.http.multipart.file-size-threshold=3 # Threshold after which files will be written to disk. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size.
spring.http.multipart.location= /
# Intermediate location of uploaded files.
spring.http.multipart.max-file-size=10MB
# Max file size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size.
spring.http.multipart.max-request-size=10MB
# Max request size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size.
spring.http.multipart.resolve-lazily=false 
# Whether to resolve the multipart request lazily at the time of file or parameter access.`enter code here`