Spring Web:通过Spring Service从服务下载文件

时间:2017-09-03 11:49:22

标签: java spring-mvc spring-web

我希望能够通过中间层Spring Web服务从遗留服务下载文件。目前的问题是我返回文件的内容而不是文件本身。

我之前使用过FileSystemResource,但我不想这样做,因为我希望Spring只重定向,而不是在服务器本身上创建任何文件。

以下是方法:

@Override
public byte[] downloadReport(String type, String code) throws Exception {
    final String usernamePassword = jasperReportsServerUsername + ":" + jasperReportsServerPassword;
    final String credentialsEncrypted = Base64.getEncoder().encodeToString((usernamePassword).getBytes("UTF-8"));
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    httpHeaders.add("Authorization", "Basic " + credentialsEncrypted);
    httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
    final HttpEntity httpEntity = new HttpEntity(httpHeaders);
    final String fullUrl = downloadUrl + type + "?code=" + code;

    return restTemplate.exchange(fullUrl, HttpMethod.GET, httpEntity, byte[].class, "1").getBody();
}

1 个答案:

答案 0 :(得分:0)

原来我在我的* Controller类中缺少这个注释参数:

produces = MediaType.APPLICATION_OCTET_STREAM_VALUE

控制器的整个方法应如下所示:

@RequestMapping(value = "/download/{type}/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<?> downloadReport(@PathVariable String type, @PathVariable String id) throws Exception {
        return new ResponseEntity<>(reportService.downloadReport(type, id), HttpStatus.OK);
    }
相关问题