简体   繁体   中英

Upload File in Spring without using form data

I am using Spring framework in Java. With it I am trying to write an API endpoint that accepts one file for upload. I do NOT want to use form data. Basically I want the following curl command to work on my endpoint

curl -XPOST localhost:8080/upload -d @local_file.data

Is there a way to do that with Spring? It seems like I want to use @RequestBody with File but that somehow seems like a horrible idea to most people. Why? How is MultipartFile different from File? Only because it supports form data?

All I can find is talk of forms and MultipartFile. Is what I'm doing somehow inherently wrong? I've done it before using Python/Django and it wasn't that hard.

It seems like the answer to my question is to use @RequestBody with a byte array. This kicks in the ByteArrayHttpMessageConverter which is one of the default HttpMessageConverters. I end up with an API endpoint like this.

@RequestMapping(value = "/upload", method=RequestMethod.POST)
public Response uploadFile(@RequestBody byte[] file) {
  ...
}

Preliminary testing works. Found it in Spring docs here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody

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