如何使用restTemplate Spring-mvc发送多部分表单数据

46

我正在尝试使用RestTemplate向Jetty运行的树莓派上传文件。在树莓派上有一个正在运行的servlet:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    PrintWriter outp = resp.getWriter();

    StringBuffer buff = new StringBuffer();

    File file1 = (File) req.getAttribute("userfile1");
    String p = req.getParameter("path");
    boolean success = false;

    if (file1 == null || !file1.exists()) {
        buff.append("File does not exist\n");
    } else if (file1.isDirectory()) {
        buff.append("File is a directory\n");
    } else {
        File outputFile = new File(req.getParameter("userfile1"));
        if(isValidPath(p)){
            p = DRIVE_ROOT + p;
            final File finalDest = new File(p
                    + outputFile.getName());
            success = false;
            try {
                copyFileUsingFileChannels(file1, finalDest);
                finalDest.setWritable(true);
                success = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (success){
                buff.append("File successfully uploaded.\n");
            }
            else{
                                    buff.append("Failed to save file.");
            }
        }
        else{
            buff.append("Invalid path.\n");
        }
    }
    outp.write(buff.toString());
}

我能够使用curl成功地完成它

curl --form userfile1=@/home/pi/src/CreateNewFolderServlet.java --form press=OK localhost:2222/pi/GetFileServlet?path="/media/"

这是应该在web应用程序上具有相同功能的方法。

@ResponseBody 
@RequestMapping(value="/upload/",method=RequestMethod.POST ,produces = "text/plain")
public String uploadFile(MultipartHttpServletRequest request2, HttpServletResponse response2){

    Iterator<String> itr =  request2.getFileNames();

     MultipartFile file = request2.getFile(itr.next());
     System.out.println(file.getOriginalFilename() +" uploaded!");

    System.out.println(file.toString()); 
     MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
    parts.add("userfile1",file);
    //reqEntity.addPart("userfile1", file);
    String path="/public/";
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    System.out.println("1");
    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(parts, headers);
    String url =  url2+"/pi/GetFileServlet?path="+path;
    System.out.println("2");
/*  restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    restTemplate.getMessageConverters().add(
            new MappingJackson2HttpMessageConverter());*/
    System.out.println("3");
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request,String.class);
    System.out.println("4");
    System.out.println("response : " +response);
    if(response==null||response.getBody().trim()==""){
        return "error";
    }
    return response.getBody();
}

这是我的输出结果:

ui-elements.html已上传!

org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@47e7673e

1

2

3

可以看到数字4没有被打印出来 控制台中没有异常。 在调试期间发现异常:

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.web.multipart.support.StandardMultipartFile["inputStream"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.web.multipart.support.StandardMultipartFile["inputStream"])

1
好的,你是否有 RestClientException 的堆栈跟踪?能否包含它? - Leandro Carracedo
控制台没有显示任何异常,但我在调试过程中找到了它。我会将其包含在上面。 - Mateusz Mańka
Lorenzo的方案对我有用。 - daddy rocks
3个回答

66

使用ByteArrayResource读取整个文件可能会在处理大文件时导致内存消耗问题。

您可以在Spring MVC控制器中使用InputStreamResource代理文件上传:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<?> uploadImages(@RequestPart("images") final MultipartFile[] files) throws IOException {
    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    String response;
    HttpStatus httpStatus = HttpStatus.CREATED;

    try {
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                map.add("images", new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename()));
            }
        }

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

        String url = "http://example.com/upload";

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
        response = restTemplate.postForObject(url, requestEntity, String.class);

    } catch (HttpStatusCodeException e) {
        httpStatus = HttpStatus.valueOf(e.getStatusCode().value());
        response = e.getResponseBodyAsString();
    } catch (Exception e) {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        response = e.getMessage();
    }

    return new ResponseEntity<>(response, httpStatus);
}

class MultipartInputStreamFileResource extends InputStreamResource {

    private final String filename;

    MultipartInputStreamFileResource(InputStream inputStream, String filename) {
        super(inputStream);
        this.filename = filename;
    }

    @Override
    public String getFilename() {
        return this.filename;
    }

    @Override
    public long contentLength() throws IOException {
        return -1; // we do not want to generally read the whole stream into memory ...
    }
}

2
令人惊讶的是,被接受的答案对我没用,但这个可以!谢谢。 - Manish Singh
@lorenzo-polidori,您能否提供一个接收MultipartInputStreamFileResource的控制器方法示例?例如,InputStreamResource的示例控制器方法。 - Krish
我使用了这种优秀的方法,并进行了一些改进(包括进一步减少内存消耗)-- 并在这里发布了后续内容:通过@Bean提供的RestTemplateBuilder进行流式上传,缓冲完整文件 - Brent Bradburn
我尝试了这种方法,但对我没有用。我在使用多部分格式的数据进行POST请求时遇到了问题。这是我的问题,如果您能指导我解决方案,那就太好了 https://dev59.com/xrHma4cB1Zd3GeqPL3j3 - Deep Lathia
1
你真是个天才。我一直无法让任何东西正常工作,但这个解决方案确实起了作用。 - RobOhRob
Spring现在附带了自己的MultipartFileResource。有关详细信息,请参见我的答案 - hzpz

17

自5.1版本起,Spring Framework提供了自己的Resource实现来处理MultipartFile。因此,您可以通过移除MultipartInputStreamFileResource类并按以下方式填充映射表来简化Lorenzo的答案

[...]

for (MultipartFile file : files) {
    if (!file.isEmpty()) {
        map.add("images", file.getResource());
    }
}

[...]

没错,那对我来说完美地解决了问题。你救了我的一天。谢谢! - Ravindra Ranwala

16
您之所以会出现异常,是因为RestTemplate的默认MessageConverters都不知道如何序列化MultipartFile文件中包含的InputStream。在通过RestTemplate发送对象时,大多数情况下都希望发送POJOs。您可以通过将MultipartFile的字节添加到MultiValueMap而不是MultipartFile本身来解决这个问题。
我认为您的servlet部分也存在问题。例如:
File file1 = (File) req.getAttribute("userfile1");

应该始终返回null,因为ServletRequest的getAttribute方法不返回请求/表单参数,而是由servlet上下文设置的属性。你确定它在您的curl示例中实际起作用吗?

这里是一个Spring MVC方法将文件转发到servlet的示例:

Servlet(尽管我测试过在Spring MVC容器中运行),改编自这里

@RequestMapping("/pi")
private void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

  final String path = request.getParameter("destination");
  final Part filePart = request.getPart("file");
  final String fileName = request.getParameter("filename");

  OutputStream out = null;
  InputStream fileContent = null;
  final PrintWriter writer = response.getWriter();

  try {
    out = new FileOutputStream(new File(path + File.separator
            + fileName));
    fileContent = filePart.getInputStream();

    int read = 0;
    final byte[] bytes = new byte[1024];

    while ((read = fileContent.read(bytes)) != -1) {
      out.write(bytes, 0, read);
    }
    writer.println("New file " + fileName + " created at " + path);

  } catch (FileNotFoundException fne) {
    writer.println("You either did not specify a file to upload or are "
            + "trying to upload a file to a protected or nonexistent "
            + "location.");
    writer.println("<br/> ERROR: " + fne.getMessage());

  } finally {
    if (out != null) {
      out.close();
    }
    if (fileContent != null) {
      fileContent.close();
    }
    if (writer != null) {
      writer.close();
    }
  }
}

Spring MVC 方法:

@ResponseBody
@RequestMapping(value="/upload/", method=RequestMethod.POST, 
        produces = "text/plain")
public String uploadFile(MultipartHttpServletRequest request) 
        throws IOException {

  Iterator<String> itr = request.getFileNames();

  MultipartFile file = request.getFile(itr.next());
  MultiValueMap<String, Object> parts = 
          new LinkedMultiValueMap<String, Object>();
  parts.add("file", new ByteArrayResource(file.getBytes()));
  parts.add("filename", file.getOriginalFilename());

  RestTemplate restTemplate = new RestTemplate();
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);

  HttpEntity<MultiValueMap<String, Object>> requestEntity =
          new HttpEntity<MultiValueMap<String, Object>>(parts, headers);

  // file upload path on destination server
  parts.add("destination", "./");

  ResponseEntity<String> response =
          restTemplate.exchange("http://localhost:8080/pi", 
                  HttpMethod.POST, requestEntity, String.class);

  if (response != null && !response.getBody().trim().equals("")) {
    return response.getBody();
  }

  return "error";
}

使用这些方法,我可以通过以下curl成功地将文件通过MVC方法上传到servlet:

curl --form file=@test.dat localhost:8080/upload/

对于Spring 3.1和3.2,我还需要处理RestTemplate在发送字节数组时的错误 - https://dev59.com/w-o6XIcBkEYKwwoYTS1D - chrismarx
你最终救了我。是的,Spring MVC 对我完美地运作。 - Tharsan Sivakumar
我尝试了这种方法,但对我没有用。我在使用多部分格式的数据进行POST请求时遇到了问题。这是我的问题,如果您能指导我解决方案,那就在这里 https://dev59.com/xrHma4cB1Zd3GeqPL3j3 - Deep Lathia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接