将数据写入JS文件并以ZIP文件格式下载

时间:2013-03-26 04:07:24

标签: javascript struts2

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

我该怎么做?

2 个答案:

答案 0 :(得分: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>

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

答案 1 :(得分: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());
}