有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpringWeb:通过Spring服务从服务下载文件

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

我以前使用过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) 个答案

  1. # 1 楼答案

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

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