Multipart文件上传Spring Boot

时间:2014-09-06 11:24:15

标签: java spring spring-mvc spring-boot multipart

我使用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<ThingRepresentation> 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 ...

<html lang="en">
<body>

    <br>
    <h2>Upload New File to this Bucket</h2>
    <form action="http://localhost:8280/appname/domains/abc/things?type=abcdef00-1111-4b38-8026-315b13dc8706" method="post" enctype="multipart/form-data">
        <table width="60%" border="1" cellspacing="0">
            <tr>
                <td width="35%"><strong>File to upload</strong></td>
                <td width="65%"><input type="file" name="file" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="submit" value="Add" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

尝试2 ....

RestTemplate template = new RestTemplate();
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
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<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("file", new FileSystemResource(path));

        HttpHeaders imageHeaders = new HttpHeaders();
        imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> imageEntity = new HttpEntity<MultiValueMap<String, Object>>(map, imageHeaders);
        ResponseEntity e=  restTemplate.exchange(uri, HttpMethod.POST, imageEntity, Boolean.class);
        System.out.println(e.toString());

7 个答案:

答案 0 :(得分:21)

您可以简单地使用控制器方法,如下所示:

@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表单客户端:

<html>
<body>
  <form action="/uploadFile" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload"> 
  </form>
</body>
</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/

答案 1 :(得分:20)

@RequestBody MultipartFile[] submissions

应该是

@RequestParam("file") MultipartFile[] submissions

这些文件不是请求正文,它们是其中的一部分,并且没有可以将请求转换为HttpMessageConverter数组的内置MultiPartFile

您也可以将HttpServletRequest替换为MultipartHttpServletRequest,这样您就可以访问各个部分的标题。

答案 2 :(得分:6)

最新版本的SpringBoot也非常容易上传多个文件。在浏览器方面,您只需要标准的HTML上传表单,但使用多个输入元素(每个要上传的文件一个,这非常重要),所有元素名称都相同(名称=&#34 ;文件&#34;如下例所示)

然后在服务器上的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);
}

这些是棘手的部分。也就是说,知道创建多个输入元素,每个输入元素都命名为&#34;文件&#34;,并且知道使用MultipartFile [](数组)作为请求参数是很难知道的事情,但它只是那个简单。我不知道如何处理MultipartFile条目,因为已经有很多文档。

答案 3 :(得分:4)

   @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("5120MB");
        factory.setMaxRequestSize("5120MB");
        return factory.createMultipartConfig();
    }

将它放在您定义bean的类中

答案 4 :(得分:1)

@RequestMapping(value="/add/image", method=RequestMethod.POST)
public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
{   
    try {
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
        Iterator<String> 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);
    }   
}

答案 5 :(得分:1)

在Controller中,您的方法应该是;

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<SaveResponse> uploadAttachment(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
....

此外,您需要更新application.yml(或application.properties)以支持最大文件大小和请求大小。

spring:
    http:
        multipart:
            max-file-size: 5MB
            max-request-size: 20MB

答案 6 :(得分:0)

添加 @RequestPart 而不是 @RequestParam

 public UploadFile upload(@RequestPart(name = "file")   MultipartFile multipartFile{
    //your code to process filee
    }