0

在我的 JSP 中,我有一个名为“下载 Zip 文件”的按钮。当我单击按钮时,我想从数据库中获取数据并将其写入 JS 文件并将其保存在文件夹中并以 ZIP 格式下载文件夹。我正在使用struts2。

我怎样才能做到这一点?

4

2 回答 2

0

试试这个:将文件下载为 Zip 的代码

ServletOutputStream servletOS = null;
    String zipFileName = null;
    try {
        servletOS = response.getOutputStream();
        final ResourceResolver resolver = request.getResourceResolver();
        zipFileName = FileDownloadHelper.getDownloadZipFileName();

        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment; filename=" + zipFileName);
        servletOS.write(FileDownloadHelper.prepareZipDownloadOutputStream(servletOS, documentUrls));
    } finally {
        if (servletOS != null) {
            servletOS.flush();
            servletOS.close();
        }
    }

public static byte[] prepareZipDownloadOutputStream(final ServletOutputStream outputStream,
        final List<String> docUrls) throws IOException {


    final byte[] buf = new byte[2048];

    String fileName;
    ZipOutputStream zipOutputStream = null;
    InputStream isInputStream = null;
    try {
        zipOutputStream = new ZipOutputStream(outputStream);

        for (final String docUrl : docUrls) {
            LOGGER.info("Reading file from DAM :  " + docUrl);

            // read this file as input stream
             isInputStream  = new FileInputStream(docUrl);

            if (isInputStream != null) {


                fileName = getFileNameFromDocumentUrl(docUrl);

                // Add ZIP entry to output stream.
                zipOutputStream.putNextEntry(new ZipEntry(fileName));
                int bytesRead;
                while ((bytesRead = isInputStream.read(buf)) != -1) {
                    zipOutputStream.write(buf, 0, bytesRead);
                }

                zipOutputStream.closeEntry();
            } e
        }
    } finally {
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.close();
        }
        if (isInputStream != null) {
            isInputStream.close();
        }
    }
    LOGGER.info("Returning buffer to be written to response output stream");
    return buf;
}

  public static String getFileNameFromDocumentUrl(final String docUrl) {
    return docUrl
            .substring(docUrl.lastIndexOf("/") + 1, docUrl.length());
}
于 2013-03-26T08:16:03.933 回答
0

一种方法是从 servlet 提供二进制数据。像这样的东西:

byte[] zipFileBytes = ...;// generate the zip file and get the bytes
response.setContentType("application/octet-stream");
response.getOutputStream().write(zipFileBytes );

然后使用标准锚元素下载文件:

<a src="url to your servlet">download the file</a>

您可能需要稍微尝试一下以匹配您的确切用例。

于 2013-03-26T05:40:05.800 回答