Multipart文件上传Spring Boot
我使用Spring Boot并希望使用Controller来接收多部分文件上传。 发送文件时,我不断收到错误415不支持的内容类型响应,并且永远不会到达控制器
There was an unexpected error (type=Unsupported Media Type, status=415). Content type 'multipart/form-data;boundary=----WebKitFormBoundary1KvzQ1rt2V1BBbb8' not supported
我尝试使用form:action在html / jsp页面中以及在使用RestTemplate的独立客户端应用程序中发送。 所有尝试都给出了相同的结果
multipart/form-data;boundary=XXXXX not supported.
从多部分文档看来,边界参数必须添加到分段上传,但这似乎与接收"multipart/form-data"
的控制器不匹配
我的控制器方法设置如下
@RequestMapping(value = "/things", method = RequestMethod.POST, consumes = "multipart/form-data" , produces = { "application/json", "application/xml" }) public ResponseEntity submitThing(HttpServletRequest request, @PathVariable("domain") String domainParam, @RequestParam(value = "type") String thingTypeParam, @RequestBody MultipartFile[] submissions) throws Exception
使用Bean安装程序
@Bean public MultipartConfigElement multipartConfigElement() { return new MultipartConfigElement(""); } @Bean public MultipartResolver multipartResolver() { org.springframework.web.multipart.commons.CommonsMultipartResolver multipartResolver = new org.springframework.web.multipart.commons.CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(1000000); return multipartResolver; }
正如您所看到的,我已将消耗类型设置为“multipart / form-data”,但是当发送multipart时,它必须具有边界参数并放置随机边界字符串。
任何人都可以告诉我如何在控制器中设置内容类型以匹配或更改我的请求以匹配我的控制器设置?
我尝试发送…尝试1 …
Upload New File to this Bucket
尝试2 ….
RestTemplate template = new RestTemplate(); MultiValueMap parts = new LinkedMultiValueMap(); parts.add("file", new FileSystemResource(pathToFile)); try{ URI response = template.postForLocation(url, parts); }catch(HttpClientErrorException e){ System.out.println(e.getResponseBodyAsString()); }
尝试3 ……
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter(); formHttpMessageConverter.setCharset(Charset.forName("UTF8")); RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add( formHttpMessageConverter ); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); MultiValueMap map = new LinkedMultiValueMap(); map.add("file", new FileSystemResource(path)); HttpHeaders imageHeaders = new HttpHeaders(); imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap> imageEntity = new HttpEntity<MultiValueMap>(map, imageHeaders); ResponseEntity e= restTemplate.exchange(uri, HttpMethod.POST, imageEntity, Boolean.class); System.out.println(e.toString());
@RequestBody MultipartFile[] submissions
应该
@RequestParam("file") MultipartFile[] submissions
这些文件不是请求主体,它们是它的一部分,并且没有内置的HttpMessageConverter
可以将请求转换为MultiPartFile
数组。
您还可以使用MultipartHttpServletRequest
替换HttpServletRequest
,这样您就可以访问各个部分的标题。
你可以简单地使用这样的控制器方法:
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody public ResponseEntity> uploadFile( @RequestParam("file") MultipartFile file) { try { // Handle the received file here // ... } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(HttpStatus.OK); } // method uploadFile
没有Spring Boot的任何其他配置。
使用以下html表单客户端:
如果要设置文件大小限制,可以在application.properties
执行此操作:
# File size limit multipart.maxFileSize = 3Mb # Total request size for a multipart/form-data multipart.maxRequestSize = 20Mb
此外,使用Ajax发送文件请看这里: http : //blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/
最新版本的SpringBoot也可以轻松上传多个文件 。 在浏览器方面,您只需要标准的HTML上传表单,但是有多个输入元素 (每个文件要上传一个,这非常重要),所有元素都具有相同的元素名称(以下示例中名称=“files”)
然后在服务器上的Spring @Controller类中, 您需要的是这样的:
@RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody ResponseEntity> upload( @RequestParam("files") MultipartFile[] uploadFiles) throws Exception { ...now loop over all uploadFiles in the array and do what you want return new ResponseEntity<>(HttpStatus.OK); }
这些是棘手的部分。 也就是说,知道创建多个输入元素,每个元素都命名为“files”,并且知道使用MultipartFile [](数组)作为请求参数是很难知道的事情,但就是这么简单。 我不会介绍如何处理MultipartFile条目,因为已经有很多文档。
@Bean MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize("5120MB"); factory.setMaxRequestSize("5120MB"); return factory.createMultipartConfig(); }
把它放在你定义bean的类中
@RequestMapping(value="/add/image", method=RequestMethod.POST) public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request) { try { MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request; Iterator it=multipartRequest.getFileNames(); MultipartFile multipart=multipartRequest.getFile(it.next()); String fileName=id+".png"; String imageName = fileName; byte[] bytes=multipart.getBytes(); BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));; stream.write(bytes); stream.close(); return new ResponseEntity("upload success", HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST); } }
在Controller中,您的方法应该是;
@RequestMapping(value = "/upload", method = RequestMethod.POST) public ResponseEntity uploadAttachment(@RequestParam("file") MultipartFile file, HttpServletRequest request) { ....
此外,您需要更新application.yml(或application.properties)以支持最大文件大小和请求大小。
spring: http: multipart: max-file-size: 5MB max-request-size: 20MB
- java.lang.ClassNotFoundException:org.apache.xmlbeans.XmlException
- Spring和MVC正确的项目结构
- 警告ArrayList是原始类型。 对generics类型ArrayList 的引用应该参数化
- 如何使用java获取weka中最近的邻居
- javax.net.ssl.SSLHandshakeException:收到致命警报:handshake_failure
- 黄瓜和Spring启动集成有错误
- Java:打开文件(Windows + Mac)
- SSLEngine unwrap()javax.crypto.BadPaddingException:坏记录MAC
- Wicket调用冗长的操作并通过ajax进行更新