2

我想要,

1)使用Spring Rest API实现一些REST 服务方法,以便从我的远程 Web 客户端上传一些文件。

2) 使用我的基于RestTemplate的远程 Web 客户端进行测试。

如果有人有任何想法,请帮助我。谢谢。

我的一些 Spring REST API 基本方法如下,

@RequestMapping(value="user/create/{userRoleName}", method=RequestMethod.POST)
    public @ResponseBody User create(@RequestBody User user, @PathVariable String userRoleName, HttpServletResponse response) { }

我的一些远程客户端的 Spring RestTemplate 基本代码如下,

Map<String, String> vars = new HashMap<String, String>();
            vars.put("userRoleName", userRoleName);
            ResponseEntity<User> REcreateUser = restTemplate.postForEntity(IMC_LAB_SKELETON_URL + "/user/create/{userRoleName}", newUser, User.class, vars);
            User createUser = REcreateUser.getBody();
4

2 回答 2

0

尝试这个:

public class FileUploadService { 
    @POST
    @Path("/file")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response upload(Attachment attachment,@Context HttpServletRequest request) {
            DataHandler handler = attachment.getDataHandler();
            try {
                InputStream stream = handler.getInputStream();
                MultivaluedMap map = attachment.getHeaders();
                OutputStream out = new FileOutputStream(new File(getFileName(map)));

                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = stream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                stream.close();
                out.flush();
                out.close();
            } catch(Exception e) {
              e.printStackTrace();
            }
        }

        return Response.ok("file uploaded").build();
    }

这可以很容易地用RestTemplate.

进口:

于 2013-04-08T17:44:21.360 回答
0
 HttpHeaders headers = new HttpHeaders();
 headers.setContentType(MediaType.MULTIPART_FORM_DATA);
 MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
 //Json Payload as String
 bodyMap.add("payload", payload);
 for (File file : fileArray) {
   bodyMap.add("file", new FileSystemResource(file));
 }
 HttpEntity<MultiValueMap<String, ?>> entity = new           
 HttpEntity<MultiValueMap<String, ?>>(bodyMap, headers);
于 2016-08-25T04:42:13.737 回答