简体   繁体   中英

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.

@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

{
  "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. You have to use -F as shown below

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

Refer post section of curl manual for more details

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

# 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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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