有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用Spring REST上传java图像

我想用RestTemplate客户端上传图片,用Spring base REST服务器获取POST请求并保存到服务器上。任何人都可以帮助我如何使用我的Spring base客户端和服务器。谢谢

我的一些Spring 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 

 }

我的远程客户端Spring 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 

共 (1) 个答案

  1. # 1 楼答案

    这是我很久以前写的一段代码(可以将文件名作为@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);
    ...
    

    使用rest模板进行测试:

    @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是必需的(我认为它需要一些ApacheCommons库,但我不确定,现在也不记得了)

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