JAVA代碼實現下載單個檔案,和下載打包檔案

來源:互聯網
上載者:User

標籤:

   

//下載單個檔案調用方法

/**
    * response
    * imgPath 下載圖片地址
    * fileName 儲存下載檔案名稱
    * @date 2015年4月14日 下午5:53:24
    */
    public static void download(HttpServletResponse response,String imgPath,String fileName){
         OutputStream out=null;
         BufferedInputStream br =null;
         try {
                // 設定響應類型為下載
                 response.setContentType("application/x-msdownload;charset=UTF-8");
                 //頁面亂碼問題
                response.setCharacterEncoding("UTF-8");
                //設定下載檔案名稱
                response.setHeader("Content-Disposition", "attachment; filename="+fileName);
                //輸入資料流
                br = new BufferedInputStream(new FileInputStream(imgPath));
                byte[] buf = new byte[1024];
                int len = 0;
                out = response.getOutputStream();
                while ((len = br.read(buf)) > 0){
                      out.write(buf, 0, len);
                      out.flush();
                }
                if(null!=out) out.close();
                if(null!=br) br.close();
         } catch (Exception e) {
               e.printStackTrace();
         }
    }

 

 

//下載打包壓縮檔調用方法

/**
     *files 需要下載問價的File 集合
    * @Description: TODO(檔案打包下載)
    */
    public static HttpServletResponse downLoadFiles(List<File> files,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            ServletContext context=request.getSession().getServletContext();
            /**這個集合就是你想要打包的所有檔案,
             * 這裡假設已經準備好了所要打包的檔案*/
            //List<File> files = new ArrayList<File>();
    
            /**建立一個臨時壓縮檔,
             * 我們會把檔案流全部注入到這個檔案中
             * 這裡的檔案你可以自訂是.rar還是.zip*/

            File file = new File(context.getRealPath("/test.rar"));
            if (!file.exists()){
                file.createNewFile(); 
            }
            response.reset();
            //response.getWriter()
            //建立檔案輸出資料流
            FileOutputStream fous = new FileOutputStream(file);  
            /**打包的方法我們會用到ZipOutputStream這樣一個輸出資料流,
             * 所以這裡我們把輸出資料流轉換一下*/
           ZipOutputStream zipOut = new ZipOutputStream(fous);
            /**這個方法接受的就是一個所要打包檔案的集合,
             * 還有一個ZipOutputStream*/
            zipFile(files, zipOut);
            zipOut.close();
            fous.close();
            return downloadZip(file,response);
        }catch (Exception e) {
                e.printStackTrace();
            }
        return response ;
    }

 

 /**
     * 把接受的全部檔案打成壓縮包
     * @param List<File>;
     * @param org.apache.tools.zip.ZipOutputStream
     */
    public static void zipFile(List files,ZipOutputStream outputStream) {
        int size = files.size();
        for(int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }

    public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
        try {
        // 以流的形式下載檔案。
        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();

        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        } catch (IOException ex) {
        ex.printStackTrace();
        }finally{
             try {
                    File f = new File(file.getPath());
                    f.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
        return response;
    }

/**
     * 根據輸入的檔案與輸出資料流對檔案進行打包
     * @param File
     * @param org.apache.tools.zip.ZipOutputStream
     */
    public static void zipFile(File inputFile,ZipOutputStream ouputStream) {
        try {
            if(inputFile.exists()) {
                /**如果是目錄的話這裡是不採取操作的,
                 * 至於目錄的打包正在研究中*/
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    //org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向壓縮檔中輸出資料  
                    int nNumber;
                    byte[] buffer = new byte[1024];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 關閉建立的流對象  
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

JAVA代碼實現下載單個檔案,和下載打包檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.