2013-08-18 73 views
0

我想用RestTemplate客户端上传图片,并使用Spring基础REST服务器获取POST请求并保存在服务器上。任何人都可以帮助我如何用我的Spring基本客户端和服务器来做到这一点。由于使用Spring REST上传图片

我的一些春天的REST API基础服务器方法如下,

@RequestMapping(value="user/upload/{imageFile}", method=RequestMethod.POST) 
    public @ResponseBody User upload(@RequestBody User user, @PathVariable File imageFile, HttpServletResponse response) { 

// TODO - How I get this image and file and save, whether I can POST this image file with User object 

} 

我的一些远程客户端的春天RestTemplate基础代码如下,

User newUser = new User(); 

Map<String, String> vars = new HashMap<String, String>(); 
      vars.put("imageFile", imageFile); 

      ResponseEntity<User> REcreateUser = restTemplate.postForEntity(IMC_LAB_SKELETON_URL + "/user/upload/{imageFile}", newUser, User.class, vars); 

      User createUser = REcreateUser.getBody(); 

// TODO - How I can POST this image file as a parameter or content of the User object 

回答

3

这是一块我之前写的代码(您可以将文件名作为@PathVariable传递):

服务器端:

@RequestMapping(value = "/file", method = RequestMethod.POST) 
public String uploadFile(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response) { 
      //add your logics here 
      //File newFile = new File("blablabla.xxx"); 
      //file.transferTo(newFile); 
... 

测试与其他模板:

@Test 
public void testFileUpload() { 

    String url = "http://blablabla.com/file"; 

    Resource resource = new ClassPathResource("images/file.xxx"); 

    MultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>(); 
    mvm.add("file", resource); 

    ResponseEntity<String> respEnt = rt.postForEntity(url, mvm, String.class); 

    //logger.info("body: " + respEnt.getBody()); 
... 

需要这个bean(我认为这需要一些阿帕奇公共图书馆,但我不知道,不记得现在)

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
     <!-- one of the properties available; the maximum file size in bytes --> 
     <property name="maxUploadSize" value="500000"/> 
    </bean> 
0

参考下面的代码你可以上传多个文件,工作正常

 <form method="POST" enctype="multipart/form-data" 
        id="fileUploadForm"> 
        <div class="controls"> 
         <div class="entry input-group col-xs-3"> 
          <input class="btn btn-primary" name="files" type="file"> 
          <span class="input-group-btn"> 
           <button class="btn btn-success btn-add" type="button"> 
            <span class="glyphicon glyphicon-plus"></span> 
           </button> 
          </span> 
         </div> 
        </div> 
       </form> 

JS

 $(document).ready(function() { 

$("#btnSubmit").click(function(event) { 

    // stop submit the form, we will post it manually. 
    event.preventDefault(); 

    fire_ajax_submit(); 

}); 

}); 

function fire_ajax_submit() { 

// Get form 
var form = $('#fileUploadForm')[0]; 

var data = new FormData(form); 

data.append("CustomField", "This is some extra data, testing"); 

// $("#btnSubmit").prop("disabled", true); 
var token = $("meta[name='_csrf']").attr("content"); 
var header = $("meta[name='_csrf_header']").attr("content"); 

$(document).ajaxSend(function(e, xhr, options) { 
    xhr.setRequestHeader(header, token); 
}); 

$.ajax({ 
    method : "POST", 
    enctype : 'multipart/form-data', 
    url : "lotConfig/lotImage", 
    data : data, 
    // http://api.jquery.com/jQuery.ajax/ 
    // https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects 
    processData : false, // prevent jQuery from automatically 
    // transforming the data into a query string 
    contentType : false, 
    cache : false, 
    timeout : 600000, 
    success : function(data) { 

     jQuery('#lotImageget').html(''); 
     getAllLotiamges(); 
     $('#updateImage').modal('hide'); 

     /* 
     * $("#result").text(data); console.log("SUCCESS : ", data); 
     * $("#btnSubmit").prop("disabled", false); 
     */ 

    }, 
    error : function(e) { 

     $("#result").text(e.responseText); 
     console.log("ERROR : ", e); 
     // $("#btnSubmit").prop("disabled", false); 

    } 
}); 

} 

春季控制器

 @PostMapping(value = "/lotImage") 
     public ResponseEntity<String> updateLotImage(
     @RequestParam("files") MultipartFile[] files, 
     RedirectAttributes redirectAttributes, HttpSession session) 
     throws IOException { 
    logger.info("--got request to update Lot Image--"); 
    StringJoiner sj = new StringJoiner(" , "); 
    for (MultipartFile file : files) { 
     if (file.isEmpty()) { 
      continue; // next pls 
     } 
     try { 

      byte[] bytes = file.getBytes(); 
      Properties prop = new Properties(); 
      String resourceName = "app.properties"; 
      ClassLoader loader = Thread.currentThread() 
        .getContextClassLoader(); 
      InputStream resourceStream = loader 
        .getResourceAsStream(resourceName); 
      try { 
       prop.load(resourceStream); 
      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
      String image_path = prop.getProperty("LOT_DESTINATION_IMG"); 

      Path path = Paths.get(image_path 
        + file.getOriginalFilename()); 
      Files.write(path, bytes); 

      sj.add(file.getOriginalFilename()); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 


    logger.info("--Image updated--"); 
    return new ResponseEntity<String>("Success", HttpStatus.OK); 

}