簡體   English   中英

如何創建zip文件並下載?

[英]How to create a zip file and download it?

我正在創建一個zip文件並下載它。 我可以下載所有文件文件,沒有任何錯誤。 但是zip中的文件根據文件實際路徑放置在嵌套文件夾中,例如C> Users> workspace> .metadata> .plugins> org.eclipse.wst.server.core> tmp0> wtpwebapps> finaldebrief我正在嘗試僅限zip'findedebrief'文件夾。 我想直接在zip文件中獲取'finaldebrief'文件夾。 有人可以幫我嗎。 提前致謝。

這是我的代碼

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    int workshopid = Integer.parseInt(request.getParameter("currentworkshopid"));

    javax.servlet.ServletContext context = getServletConfig().getServletContext();
    String path = context.getRealPath("finaldebrief");

    try 
    { 
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=finaldebrief.zip");

        ZipOutputStream zos = new 
               ZipOutputStream(response.getOutputStream()); 

        zipDir(path + "/", zos); 

        zos.close(); 
    } 
    catch(Exception e) 
    { 
        e.printStackTrace();
    } 

}

public void zipDir(String dir2zip, ZipOutputStream zos) 
{
    try 
    { 
        //create a new File object based on the directory we have to zip File    
        File zipDir = new File(dir2zip); 
        //get a listing of the directory content 
        String[] dirList = zipDir.list(); 
        byte[] readBuffer = new byte[2156]; 
        int bytesIn = 0; 
        //loop through dirList, and zip the files 
        for(int i=0; i<dirList.length; i++) 
        { 
            File f = new File(zipDir, dirList[i]); 
            if(f.isDirectory()) 
            { 
                //if the File object is a directory, call this 
                //function again to add its content recursively 
                String filePath = f.getPath();
            //  String filePath = f.getCanonicalPath();

                zipDir(filePath, zos);
                //loop again 
                continue; 
            } 
            //if we reached here, the File object f was not  a directory 
            //create a FileInputStream on top of f 
            FileInputStream fis = new FileInputStream(f); 
            // create a new zip entry 
            ZipEntry anEntry = new ZipEntry(f.getPath()); 
            //place the zip entry in the ZipOutputStream object 
            zos.putNextEntry(anEntry); 
            //now write the content of the file to the ZipOutputStream 
            while((bytesIn = fis.read(readBuffer)) != -1) 
            { 
                zos.write(readBuffer, 0, bytesIn); 
            } 
            //close the Stream 
            fis.close(); 
        } 
    } 
    catch(Exception e) 
    { 
        e.printStackTrace(); 
    } 
}

在線內

ZipEntry anEntry = new ZipEntry(f.getPath());

你指定zip文件中的路徑(即f.getPath() )。 如果你想要一個更短的路徑或者根本f.getName()操作這個部分(例如f.getName() )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM