用于发布jar文件的Spring REST API

时间:2015-04-20 07:25:28

标签: spring rest post spring-4

我正在使用RESTful端点进行某些文件操作。我想通过REST发布一个jar文件到我的服务,我试过下面的方法,但它仍然失败,我几乎尝试谷歌搜索,但找不到任何解决方案。

@RestController
public class MyController {
 ...

@RequestMapping(value="/jobs/upload", method=RequestMethod.POST)
public @ResponseBody ResponseEntity<Void> handleFileUpload(HttpEntity<byte[]> requestEntity){
    byte[] payload = requestEntity.getBody();
    InputStream logo = new ByteArrayInputStream(payload);
    HttpHeaders headers = requestEntity.getHeaders();
    return ResponseEntity.ok().build();
 }
...
}

卷曲命令curl -X POST --data-binary @/Users/path/to-jar/test-jar.jar localhost:8008/ctx/jobs/upload

[编辑] :如果我必须通过--data-binary实现,我的代码应该如何?

我无法继续前进,任何人都可以帮忙。我在MultiPart上看到了很多解决方案,但我无法适应它。

2 个答案:

答案 0 :(得分:1)

您需要为MUltipart配置一个servlet:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="200000"/>
</bean>

然后在您的REST服务中

@RequestMapping(value="/jobs/upload", method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<Void> handleFileUpload(@RequestParam("file") MultipartFile multipartFile,
                                             HttpServletRequest request) {
    ...
}

答案 1 :(得分:0)

尝试以下解决方案

@RequestMapping(value = APIURIConstants.GET_JAR, method = RequestMethod.GET)
    public ResponseEntity<byte[]> getJar(

            HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        String fullPath = objPollBookService.getSignatureFileName(electionID);
        System.out.println("Path=" + fullPath);

        byte[] content = null;
        try {
            URL link = new URL(fullPath);
            InputStream in = new BufferedInputStream(link.openStream());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int n = 0;
            while (-1 != (n = in.read(buf))) {
                out.write(buf, 0, n);
            }
            out.close();
            in.close();
            content = out.toByteArray();

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

        HttpHeaders headers = new HttpHeaders();
        String mimeType = context.getMimeType(fullPath);
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }
        headers.setContentType(MediaType.parseMediaType(mimeType));
        String filename = FilenameUtils.getBaseName(fullPath);
        headers.setContentDispositionFormData(filename, filename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(content,
                headers, HttpStatus.OK);
        return response;
    }