[英]Download Multiple files Java Spring
我試圖在我的 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();
}
奇怪的是,根據導航器的不同,我得到了不同的結果。 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;
}
下載 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();
}
}
玩得開心,以防萬一,讓我知道。
更新
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();
}
您可以使用 multipart/x-mixed-replace 內容類型來完成。 您可以添加類似response.setContentType("multipart/x-mixed-replace;boundary=END");
並循環遍歷文件並將每個文件寫入響應輸出流。 您可以查看此示例以供參考。
另一種方法是創建一個 REST 端點,讓您下載一個文件,然后為每個文件重復調用該端點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.