Spring Boot REST POST API 发送文件

3

我刚接触Spring Rest,正在尝试创建一个REST POST API,在这个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 文件并选择表单数据 (在 Postman 中) 调用此 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"
}

你是怎么传递 file 参数的?请发布请求。 - Maroun
curl -X POST http://localhost:8080/order \ -d json='{"name":"john", "lastNane":"doe"}'请将上述命令翻译为中文: curl -X POST http://localhost:8080/order \ -d json='{"name":"john", "lastNane":"doe"}' - krs8888
如果我想附加一个包含JSON的文本文件,我应该使用requestBody吗? - krs8888
如果您已经使用了RestController,则无需使用requestBody。 - harshavmb
2个回答

6

问题不在于您编写的接受请求的代码,而是在于请求方式。

-d 用于传递数据。您需要使用下面所示的 -F

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

请参阅curl手册中的帖子部分,以获取更多详细信息。


-1

请确认您是否拥有以下物品:

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

而在 applications.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`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接