我从事一个 Spring 项目来制作一个 Web 应用程序,因此有一个 Tomcat 服务器允许我使用我的 Web 应用程序。
我在这个网络应用程序上有两个功能,第一个功能允许我在 Postgresql 数据库上上传文件(它工作正常)。但在那之后,我希望能够下载这个文件。
这是我的服务方法。
public byte[] download(Integer id){
Line line = getById(Line.class, id);
int blobLenght;
byte[] fileToReturn = null;
Blob file = line.getFile();
blobLenght = (int)file.length();
fileToReturn = file.getBytes(1,blobLenght);
return fileToReturn;
}
在我的 RestController 上,我有一个带有注释 @RequestMapping 的方法。 这个方法返回一个 ResponseEntity。在之后的方法中,lineService 被注入(inject)(@Autowired)在我的类的顶部。
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<?> download(@RequestParam("id" Integer id)
{
byte[] fileToDownload = lineService.download(id);
return new ResponseEntity<byte[]>(fileToDownload,HttpStatus.OK);
}
我已尽力简化该方法。
这是我的问题。事实上,我意识到一种方法在我逐一提出一些请求时有效。但是,服务器必须能够支持同时接收大量请求。现在,当我同时测试多个请求时,我遇到了 OutOfMemoryError :Java 堆空间。
我尝试在“下载”方法上实现 Stream,但出现相同的错误。我对流的实现不能很好地完成。
我尝试了在互联网上找到的许多解决方案,这是我实现的最后一个:
public ResponseEntity<byte[]> download(Integer id){
Line line = getById(Line.class, id);
HttpHeaders headers = new HttpHeaders();
InputStream is = line.getFile().getBinaryStream;
byte[] fileToReturn = IOUtils.toByteArray(is);
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(fileToDownload,HttpStatus.OK);
return responseEntity;
}
你知道我如何更新我的程序来满足项目的要求吗?
如果我进展顺利,你能告诉我我的错误在哪里吗?或者你有什么建议吗?
感谢您的帮助!
下午。
最佳答案
我用流修改了“下载”方法,它按照我想要的方式正常工作。
public void download(Integer id, HttpServletResponse response){
Line line = getById(Line.class, id);
InputStream is = line.getFile().getBinaryStream;
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
}
我的 Controller 是这样的:
public ResponseEntity<?> download(@RequestParam("id") Integer id, HttpServletResponse response)
{
lineService.download(id,response);
return new ResponseEntity<>(HttpStatus.OK);
}
关于java - Spring : Download file from REST controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51519160/