Spring Web:通过 Spring 服务从服务下载文件
Spring Web: Download a File from a service via a Spring Service
我希望能够通过中间层 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();
}
原来我的 *Controller 中缺少这个注释参数 class:
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);
}
我希望能够通过中间层 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();
}
原来我的 *Controller 中缺少这个注释参数 class:
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);
}