2017-09-03 162 views
0

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

我以前使用过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(); 
} 
+0

*目前的问题是我回来的文件的内容,而不是文件本身*:那是什么N +你在做什么,你期望发生什么,取而代之的是什么? –

+0

我正尝试下载位于另一个Web服务中的文件。我想下载文件。我正在显示文件的原始内容。 –

+0

这回答了“发生了什么事情”部分。你预计会发生什么? –

回答

0

原来我错过了我的*控制器类此批注参数:

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