简体   繁体   English

spring-boot REST POST API发送文件

[英]spring-boot REST POST API to send a file

I am new to spring rest and trying to create a REST POST API where the user can send a file to the server. 我刚接触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!";
}

But I when make a call to this API by uploading a order.txt file and selecting form-data (in postman) I get this error 但是,当我通过上传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"
}

Problem is not with your code which accepts the request. 问题不在于您的接受请求的代码。 It is with the request how you are making. 这是与您的要求如何。

-d is used to pass the data. -d用于传递数据。 You have to use -F as shown below 您必须使用-F ,如下所示

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

Refer post section of curl manual for more details 请参阅curl手册的发布部分以获取更多详细信息

Verify if you have these items: 验证是否有以下项目:

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

And in the pplications.properties 并在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`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM