文件下載工具類 DownLoadUtil 實戰


package com.cloud.mina.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;
/***
 * 下載文件工具類
 */

public class DownLoadUtil {
    private static final String CONTENT_TYPE = "application/x-msdownload";
    /**
     * 下載文件
     * @param response HttpServletResponse
     * @param title 下載時候的文件名稱
     * @param file 要下載的文件對象
     * @return true 下載成功    false 下載失敗
     */
    public static boolean downLoadFile(HttpServletResponse response,String filename,File file){
        boolean result = true;
        FileInputStream input = null;
        OutputStream out = null;
        try {
            //設置response的編碼方式
            response.setContentType(CONTENT_TYPE);
            //寫明要下載的文件的大小
            response.setContentLength((int)file.length());
            //設置附加文件名
            response.setHeader("Content-Disposition","attachment;filename=\""+new String
                    (filename.getBytes("UTF-8"),"iso-8859-1")+"\"");
            //讀出文件到i/o流
            input =new FileInputStream(file);
            //從response對象中得到輸出流,准備下載
            out = response.getOutputStream();
            if(input!=null && out!=null){    // 判斷輸入或輸出是否准備好
                int temp = 0 ;    
                try{
                    while((temp=input.read())!=-1){    // 開始拷貝
                        out.write(temp) ;    // 邊讀邊寫
                    }
                }catch(IOException e){
                    e.printStackTrace() ;
                    result = false;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            result = false;
        } catch (IOException e) {
            result = false;
            e.printStackTrace();
        } finally{
            if(input!=null){
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    result = false; 
                }
            }
            if(out!=null){
                try {
                    out.flush();
                    out.close();//關閉輸出流
                } catch (IOException e) {
                    e.printStackTrace();
                    result = false; 
                }
            }
            
        }
        return result;
    }
}
 

原文地址;https://blog.csdn.net/qxqxqzzz/article/details/97008529


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM