【问题标题】:Download Multiple files Java Spring下载多个文件 Java Spring
【发布时间】:2016-04-27 09:46:24
【问题描述】:

我正在尝试在我的 spring-mvc 应用程序中使用一个 http get 请求下载多个文件。

我看过其他帖子,说您可以压缩文件并发送此文件,但在我的情况下并不理想,因为该文件不能从应用程序直接访问。要获取文件,我必须查询 REST 接口,该接口从 hbase 或 hadoop 流式传输文件。

我可以拥有大于 1 Go 的文件,因此将文件下载到存储库中、压缩它们并将它们发送到客户端会太长。 (考虑到大文件已经被压缩了,压缩不会压缩它们)。

我看到herethere 可以使用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 中什么都没有发生,在 Firefox 中,我收到一个提示,要求下载每个文件,但它没有正确的类型或正确的名称(控制台中也没有)。

我的代码中是否有任何错误?如果没有,还有其他选择吗?

编辑

我也看到了这个帖子:Unable to send a multipart/mixed request to spring MVC based REST service

编辑 2

这个文件的内容是我想要的,但是为什么我取不到正确的名字,为什么chrome不能下载任何东西呢?

【问题讨论】:

  • 您可以在JS中循环下载请求,每个请求完成后都会触发新的下载。我认为这似乎比破解触发多次下载更容易。
  • @WeareBorg 我只有js的基础知识,你能给我一些资源吗?
  • 很遗憾,我是后端开发人员,连 JS 都不知道。如果你想用 Java,我可以给你 ZIP 下载的代码,我有...
  • @WeareBorg 只是一个问题。在我的情况下,zip 步骤是否涉及,等待从 rest 界面到 web 应用程序的完整下载,然后将 zip 转发到客户端?
  • @WeareBorg 我目前正在做的想法是纯流式传输,因此我不会将数据保存在服务器上(缓存除外)。但我无法进行多部分工作。现在解决了

标签: java spring http download


【解决方案1】:

这是您可以通过 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();
}

【讨论】:

    【解决方案2】:

    您可以使用 multipart/x-mixed-replace 内容类型来做到这一点。 您可以像response.setContentType("multipart/x-mixed-replace;boundary=END"); 一样添加它并循环浏览文件并将每个文件写入响应输出流。 您可以查看此example 以供参考。

    另一种方法是创建一个 REST 端点,让您可以下载一个文件,然后为每个文件单独重复调用此端点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      相关资源
      最近更新 更多