简体   繁体   English

创建并下载Zip文件java

[英]create and download the Zip file java

In my application there are no of documents(pdf) for a particular tender. 在我的申请中,没有特定投标的文件(pdf)。 I need to create a zip file from those pdf files and allow user to download it. 我需要从那些pdf文件创建一个zip文件,并允许用户下载它。

Application is done in JavaEE with struts and mysql. 应用程序在JavaEE中使用struts和mysql完成。 when user clicks the download button this action class gets called. 当用户单击下载按钮时,将调用此操作类。 The code does not give any exceptions but it does not prompt user to download anything either. 该代码不提供任何例外,但它也不会提示用户下载任何内容。

Please help me find what is wrong in the code. 请帮我找到代码中的错误。

Following is the source code of my action class.. 以下是我的动作类的源代码..

public class ActDownloadDocZip extends Action {
static Logger logger = Logger.getLogger(ActDownloadDocZip.class);

public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String realPath = getServlet().getServletContext().getRealPath(
            "/WEB-INF/log4jConfiguration.xml");
    DOMConfigurator.configure(realPath);
    logger.info("In ActDownloadDocZip....");
    ActionForward forward = null;
    HttpSession session = request.getSession();
    // get a db connection
    Connection conn = null;
    String[][] nameFile = null;
    String tenderNo = "";
    try {
        conn = ProxoolConnection.getProxoolConnectionSLT();
        tenderNo = request.getParameter("tenderNo");
        // File fileex=new File("xxx.zip");
        FileOutputStream zipFile = new FileOutputStream(new File("xxx.zip"));
        ZipOutputStream output = new ZipOutputStream(zipFile);
        // call getPdfFiles method here
        ILoadTenders ld = new LoadTenders();
        nameFile = ld.getPdfFileListToTender(conn, tenderNo);//this method brings back the relevant pdf file names and paths((pdfname1,pdfpath1),(pdfname2,pdfpath2))
        for (int i = 0; i < nameFile.length; i++) {
            ZipEntry zipEntry = new ZipEntry(nameFile[i][0].trim());
            output.putNextEntry(zipEntry);
            FileInputStream pdfFile = new FileInputStream(new File(
                    nameFile[i][1].trim()));
            IOUtils.copy(pdfFile, output); 
            pdfFile.close();
            output.closeEntry();
        }
        output.finish();
        output.close();
    } catch (SQLException e) {
        System.out.println("actDownloadDocZip " + e);
        logger.fatal(e.getMessage());
    } catch (Exception e) {
        System.out.println("actDownloadDocZip1 " + e);
        logger.fatal(e.getMessage());
    } finally {
        if (conn != null) {
            ProxoolConnection.closeProxoolConnectionSLT(conn);
        }
    }
    forward = mapping.findForward("publicdashboard");
    return forward;
  }
}

Done :) I was already there... just had to give a proper path and download it.... 完成:)我已经在那里......只需要给出正确的路径并下载它....

Here the action class again: 这里是动作类:

package com.affno.etender.frontend;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import com.affno.util.proxool.ProxoolConnection;

public class ActDownloadDocZip extends Action {
    static Logger logger = Logger.getLogger(ActDownloadDocZip.class);

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        String realPath = getServlet().getServletContext().getRealPath(
                "/WEB-INF/log4jConfiguration.xml");
        DOMConfigurator.configure(realPath);
        logger.info("In ActDownloadDocZip....");

        ActionForward forward = null;
        HttpSession session = request.getSession();

        // get a db connection
        Connection conn = null;

        String[][] nameFile = null;

        String tenderNo = "";

        ////
        FileOutputStream fos = null;
        ZipOutputStream zipOut = null;
        FileInputStream fis = null;

        MessageResources messages = MessageResources.getMessageResources("resources.Upload");
        String dirzip = messages.getMessage("save.dir");
        tenderNo = request.getParameter("tenderNo").trim();
        String zipFolderName =tenderNo + ".zip";
        String filepathzipped = dirzip + zipFolderName;

        try {
            conn = ProxoolConnection.getProxoolConnectionSLT();

            fos = new FileOutputStream(filepathzipped);
            zipOut = new ZipOutputStream(new BufferedOutputStream(fos));

            ILoadTenders ld = new LoadTenders();
            nameFile = ld.getPdfFileListToTender(conn, tenderNo);

            for (int i = 0; i < nameFile.length; i++){
                File input = new File(nameFile[i][1].trim());
                fis = new FileInputStream(input);
                ZipEntry ze = new ZipEntry(input.getName());
                System.out.println("Zipping the file: "+input.getName());
                zipOut.putNextEntry(ze);
                byte[] tmp = new byte[4*1024];
                int size = 0;
                while((size = fis.read(tmp)) != -1){
                    zipOut.write(tmp, 0, size);
                }
                zipOut.flush();
                fis.close();
            }
            zipOut.close();
            System.out.println("Done... Zipped the files...");
            //zip created

            //downloading the zip
            File file = new File(filepathzipped);
            if(!file.exists()){
                System.out.println("file not found");
            }
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition","attachment; filename=\"" + zipFolderName + "\"");

            OutputStream out = response.getOutputStream();
            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) > 0){
               out.write(buffer, 0, length);
            }
            in.close();
            out.flush();    
        }
        ////
         catch (SQLException e) {
            System.out.println("actDownloadDocZip " + e);
            logger.fatal(e.getMessage());
        } catch (Exception e) {
            System.out.println("actDownloadDocZip1 " + e);
            logger.fatal(e.getMessage());
        } finally {
            if (conn != null) {
                ProxoolConnection.closeProxoolConnectionSLT(conn);
            }
        }

        forward = mapping.findForward("publicdashboard");
        /*
         * if (forward != null) { forward = new ActionForward(forward.getPath()
         * +"servlet/DownloadServlet?" + zipFile, true); }
         */
        return forward;
    }
}
  1. Intercept the request while downloading the report and copy the download url and hit. 下载报告时拦截请求并复制下载URL并点击。
  2. Code for prevent the direct access of the url for downloading any file 防止直接访问url以下载任何文件的代码

Implementation 履行

if (param.equals("downloadfile")) {
    session = request.getSession();
    relativePath = request.getRealPath("/");
    String filePathName = relativePath + "FILES\\EXCEL\\ASC_Mapping_" + user.getLoginID() + ".zip";
    System.out.println("guddu 1 " + filePathName);

    if (filePathName == null || filePathName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }

    File file1 = new File(filePathName);
    if (!file1.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }

    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment;filename=ASC_Mapping_" + user.getLoginID() + ".zip");

    FileInputStream fileInputStream = new FileInputStream(file1);
    OutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[4096];
    int read = 0;
    while ((read = fileInputStream.read(bufferData)) > 0) {
        os.write(bufferData, 0, read);
    }

    os.close();
    fileInputStream.close();
    response.flushBuffer();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM