我正在尝试在我的Spring-MVC应用程序中使用一个HTTP get请求来下载多个文件。
我已经查看了其他帖子,说你可以压缩文件并发送这个文件,但在我的情况下不理想,因为文件无法直接从应用程序访问。要获取文件,我必须查询REST接口,该接口从hbase或hadoop流式传输文件。
我可能有超过1 GB的文件,因此将文件下载到存储库中,将其压缩并将其发送到客户端需要太长时间。(考虑到大文件已经被压缩,再次压缩不会使它们更小)。
我看到这里和那里说可以使用multipart-response
一次下载多个文件,但我无法得到任何结果。这是我的代码:
String boundaryTxt = "--AMZ90RFX875LKMFasdf09DDFF3";
response.setContentType("multipart/x-mixed-replace;boundary=" + boundaryTxt.substring(2));
ServletOutputStream out = response.getOutputStream();
// write the first boundary
out.write(("\r\n"+boundaryTxt+"\r\n").getBytes());
String contentType = "Content-type: application/octet-stream\n";
for (String s:files){
System.out.println(s);
String[] split = s.trim().split("/");
db = split[1];
key = split[2]+"/"+split[3]+"/"+split[4];
filename = split[4];
out.write((contentType + "\r\n").getBytes());
out.write(("\r\nContent-Disposition: attachment; filename=" +filename+"\r\n").getBytes());
InputStream is = null;
if (db.equals("hadoop")){
is = HadoopUtils.get(key);
}
else if (db.equals("hbase")){
is = HbaseUtils.get(key);
}
else{
System.out.println("Wrong db with name: " + db);
}
byte[] buffer = new byte[9000]; // max 8kB for http get
int data;
while((data = is.read(buffer)) != -1) {
out.write(buffer, 0, data);
}
is.close();
// write bndry after data
out.write(("\r\n"+boundaryTxt+"\r\n").getBytes());
response.flushBuffer();
}
// write the ending boundary
out.write((boundaryTxt + "--\r\n").getBytes());
response.flushBuffer();
out.close();
}
奇怪的是,我的浏览器会得到不同的结果。在Chrome中什么都没有发生(查看了控制台),而在Firefox中,我得到了一个提示,要求为每个文件下载,但它既没有正确的类型也没有正确的名称(控制台中也没有任何内容)。
我的代码有什么错误吗?如果没有,有没有其他替代方法?
编辑
我还看到了这篇文章:无法将multipart/mixed请求发送到基于Spring MVC的REST服务 编辑2
![Firefox结果](https://istack.dev59.com/5zeTy.webp)