简体   繁体   English

在Spring中上传文件而不使用表单数据

[英]Upload File in Spring without using form data

I am using Spring framework in Java. 我在Java中使用Spring框架。 With it I am trying to write an API endpoint that accepts one file for upload. 我正在尝试编写一个可以接受一个文件上传的API端点。 I do NOT want to use form data. 我不想使用表单数据。 Basically I want the following curl command to work on my endpoint 基本上我想让以下curl命令在我的端点上工作

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

Is there a way to do that with Spring? Spring有办法做到这一点吗? It seems like I want to use @RequestBody with File but that somehow seems like a horrible idea to most people. 似乎我想将@RequestBody与File一起使用,但是对于大多数人来说,这似乎是一个可怕的想法。 Why? 为什么? How is MultipartFile different from File? MultipartFile与File有何不同? Only because it supports form data? 仅因为它支持表单数据?

All I can find is talk of forms and MultipartFile. 我所能找到的就是表格和MultipartFile。 Is what I'm doing somehow inherently wrong? 我正在做的事情本质上是错误的吗? I've done it before using Python/Django and it wasn't that hard. 我在使用Python / Django之前就已经做到了,而且还不难。

It seems like the answer to my question is to use @RequestBody with a byte array. 似乎我的问题的答案是将@RequestBody与字节数组一起使用。 This kicks in the ByteArrayHttpMessageConverter which is one of the default HttpMessageConverters. 这将启动ByteArrayHttpMessageConverter,它是默认HttpMessageConverters之一。 I end up with an API endpoint like this. 我最终得到了这样的API端点。

@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 在以下位置的Spring文档中找到了它: http : //docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody

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

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