Whi*_*ret 6 java spring http download
我试图在我的 spring-mvc 应用程序中使用一个 http get 请求下载多个文件。
我看过其他帖子,说你可以压缩文件并发送这个文件,但在我的情况下并不理想,因为文件不能从应用程序直接访问。要获取文件,我必须查询 REST 接口,该接口从 hbase 或 hadoop 流式传输文件。
我可以拥有大于 1 Go 的文件,因此将文件下载到存储库、压缩它们并将它们发送到客户端会太长。(考虑到大文件已经是 zip,压缩不会压缩它们)。
我在这里和那里看到您可以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();
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,根据导航器的不同,我得到了不同的结果。在 Chrome(查看控制台)和 Firefox 中没有发生任何事情,我收到提示要求下载每个文件,但它没有正确的类型和正确的名称(控制台中也没有)。
我的代码中是否有任何错误?如果没有,有没有其他选择?
编辑
我还看到了这篇文章:无法向基于 Spring MVC 的 REST 服务发送多部分/混合请求
编辑 2
这个文件的内容是我想要的,但是为什么我不能得到正确的名字,为什么chrome不能下载任何东西?
这是通过 zip 下载的方法:
try {
List<GroupAttachments> groupAttachmentsList = attachIdList.stream().map(this::getAttachmentObjectOnlyById).collect(Collectors.toList()); // Get list of Attachment objects
Person person = this.personService.getCurrentlyAuthenticatedUser();
String zipSavedAt = zipLocation + String.valueOf(new BigInteger(130, random).toString(32)); // File saved location
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipSavedAt);
ZipOutputStream zos = new ZipOutputStream(fos);
GroupAttachments attachments = getAttachmentObjectOnlyById(attachIdList.get(0));
for (GroupAttachments groupAttachments : groupAttachmentsList) {
Path path = Paths.get(msg + groupAttachments.getGroupId() + "/" +
groupAttachments.getFileIdentifier()); // Get the file from server from given path
File file = path.toFile();
FileInputStream fis = new FileInputStream(file);
zos.putNextEntry(new ZipEntry(groupAttachments.getFileName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
zos.close();
return zipSavedAt;
}
} catch (Exception ignored) {
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
下载 zip 的控制器方法:
@RequestMapping(value = "/URL/{mode}/{token}")
public void downloadZip(HttpServletResponse response, @PathVariable("token") String token,
@PathVariable("mode") boolean mode) {
response.setContentType("application/octet-stream");
try {
Person person = this.personService.getCurrentlyAuthenticatedUser();
List<Integer> integerList = new ArrayList<>();
String[] integerArray = token.split(":");
for (String value : integerArray) {
integerList.add(Integer.valueOf(value));
}
if (!mode) {
String zipPath = this.groupAttachmentsService.downloadAttachmentsAsZip(integerList);
File file = new File(zipPath);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\"" + person.getFirstName() + ".zip" + "\"");
InputStream is = new FileInputStream(file);
FileCopyUtils.copy(IOUtils.toByteArray(is), response.getOutputStream());
response.flushBuffer();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
玩得开心,如有疑问,让我知道。
更新
ZIP 文件中的字节数组。您可以在循环中使用此代码,就像我给出的第一个方法一样:
public static byte[] zipBytes(String filename, byte[] input) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry(filename);
entry.setSize(input.length);
zos.putNextEntry(entry);
zos.write(input);
zos.closeEntry();
zos.close();
return baos.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23600 次 |
| 最近记录: |