Spring REST API 用于发布 jar 文件

Spring REST API for posting jar file

我正在使用 RESTful 端点进行一些文件操作。我想通过 REST post 一个 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 上看到了很多解决方案,但我无法适应它。

尝试以下解决方案

@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;
    }

您需要为 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) {
    ...
}