下载多个文件Java Spring

时间:2016-04-27 09:46:24

标签: java spring http download

我正在尝试使用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中,我得到了一个提示,要求为每个文件下载,但它没有正确的类型,也没有正确的名称(控制台中也没有)。

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

修改

我也看过这篇文章:Unable to send a multipart/mixed request to spring MVC based REST service

修改2

firefox result

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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

另一种方法是创建一个REST端点,该端点将允许您下载一个文件,然后针对每个文件分别重复调用该端点。