springmvc RestTemplate文件上传

转自:http://blog.csdn.net/mhmyqn/article/details/26395743

在使用springmvc提供rest接口实现文件上传时,有时为了测试需要使用RestTemplate进行调用,那么在使用RestTemplate调用文件上传接口时有什么特别的地方呢?实际上只需要注意一点就行了,就是创建文件资源时需要使用org.springframework.core.io.FileSystemResource类,而不能直接使用java.io.File对象。

 

Controller中的rest接口代码如下:

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. @ResponseBody  
  2. @RequestMapping(value = "/upload.do", method = RequestMethod.POST)  
  3. public String upload(String fileName, MultipartFile jarFile) {  
  4.     // 下面是测试代码  
  5.     System.out.println(fileName);  
  6.     String originalFilename = jarFile.getOriginalFilename();  
  7.     System.out.println(originalFilename);  
  8.     try {  
  9.         String string = new String(jarFile.getBytes(), "UTF-8");  
  10.         System.out.println(string);  
  11.     } catch (UnsupportedEncodingException e) {  
  12.         e.printStackTrace();  
  13.     } catch (IOException e) {  
  14.         e.printStackTrace();  
  15.     }  
  16.     // TODO 处理文件内容...  
  17.     return "OK";  
  18. }  


使用RestTemplate测试上传代码如下:

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. @Test  
  2. public void testUpload() throws Exception {  
  3.     String url = "http://127.0.0.1:8080/test/upload.do";  
  4.     String filePath = "C:\\Users\\MikanMu\\Desktop\\test.txt";  
  5.   
  6.     RestTemplate rest = new RestTemplate();  
  7.     FileSystemResource resource = new FileSystemResource(new File(filePath));  
  8.     MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();  
  9.     param.add("jarFile", resource);  
  10.     param.add("fileName""test.txt");  
  11.   
  12.     String string = rest.postForObject(url, param, String.class);  
  13.     System.out.println(string);  
  14. }  

其中:

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. String string = rest.postForObject(url, param, String.class);  

可以换成:

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String,Object>>(param);  
  2. ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);  
  3. System.out.println(responseEntity.getBody());  

猜你喜欢

转载自coffeehot.iteye.com/blog/2107300