当前位置: 首页 > 面试题库 >

如何使用RestTemplate Spring-mvc发送Multipart表单数据

归德厚
2023-03-14
问题内容

我正在尝试使用Jetty将带有RestTemplate的文件上传到Raspberry Pi。在Pi上,正在运行一个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 --form userfile1=@/home/pi/src/CreateNewFolderServlet.java --form press=OK localhost:2222/pi/GetFileServlet?path="/media/"

这是应该在webapp上具有相同功能的方法。

@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"])

问题答案:

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 ...
    }
}


 类似资料:
  • 问题内容: 我正在一个ASP.NET MVC网站上工作,该网站的表单允许使用表单标签上的multipart / form data enctype选项上传文件,如下所示 我将如何编写此代码来代替进行ASP.NET MVC Ajax表单发布? 问题答案: 您可以使用其他一些上传器(例如jQuery多个文件上传器)(我更喜欢这种方式,而且我不喜欢使用MS Ajax) 采用: 但是在第二种情况下,我不确

  • 我正在尝试用RestTemplate上传一个文件到带有Jetty的Raspberry Pi。在Pi上有一个运行的servlet: 这是我得到的输出: UI-elements.html已上传! org.springframework.web.multipart.support.StandardMultipartTtpServletRequest$StandardMultipartFile@47e76

  • 我开发了一个应用程序。在我的应用程序中,我从相机或画廊拍摄一张图像。我想使用多部分发布图像到服务器,但图像不发布它。我的帖子数据如下

  • 无法在react native expo应用程序中以“Multipart/formdata”内容类型发送表单数据。当我们在react-native应用程序的post请求中发送formData对象时,我们无法获取req。需求主体。来自节点后端的文件

  • 问题内容: 我正在开发使用不同服务其余部分的图形界面(用Java编写)。我必须调用这样的服务: 呼叫服务: 当我从Angularjs服务文件中请求时,如果服务具有Content-Type = multipart / form- data,则会收到错误400(错误请求) 如果服务的Content-Type =“ application / x-www-form-urlencoded; charset

  • 问题内容: 我在使用jQuery的ajax函数将文件发送到服务器端PHP脚本时遇到问题。可以获取File- List,但是如何将此数据发送到服务器呢?使用文件输入时,服务器端php脚本上的结果数组()为0()。 我知道这是可能的(尽管直到现在我还没有找到任何jQuery解决方案,只有Prototye代码(http://webreflection.blogspot.com/2009/03/safar