我有三台机器:
我如何才能直接(不保存在第二服务器上的文件)下载文件从第一服务器到客户的机器?
在第二台服务器上,我可以从第一台服务器获得一个ByteArrayOutputStream文件,我可以使用REST服务将这个流进一步传递给客户端吗?
它会这样工作吗?
基本上,我想要实现的是允许客户端使用第二服务器上的REST服务从第一服务器下载一个文件(因为没有客户端到第一服务器的直接访问),只使用数据流(所以没有数据与第二服务器的文件系统接触)。
现在我尝试使用EasyStream库:
final FTDClient client = FTDClient.getInstance();
try {
final InputStreamFromOutputStream <String> isOs = new InputStreamFromOutputStream <String>() {
@Override
public String produce(final OutputStream dataSink) throws Exception {
return client.downloadFile2(location, Integer.valueOf(spaceId), URLDecoder.decode(filePath, "UTF-8"), dataSink);
}
};
try {
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
StreamingOutput output = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws IOException, WebApplicationException {
int length;
byte[] buffer = new byte[1024];
while ((length = isOs.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
}
};
return Response.ok(output, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
}UPDATE2
因此,现在使用自定义MessageBodyWriter的代码看起来很简单:
ByteArrayOutputStream baos = new ByteArrayOutputStream(2048) ;
client.downloadFile(location, spaceId, filePath, baos);
return Response.ok(baos).build();但是,在尝试处理大型文件时,我也会遇到相同的堆错误。
UPDATE3终于成功了!StreamingOutput成功了。
谢谢你@peeskillet!非常感谢!
发布于 2016-11-10 10:47:20
请参阅:
@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {
// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();
// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");
// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}https://stackoverflow.com/questions/29712554
复制相似问题