Servlet下載檔案

孫群發表於2013-10-27

Java Servlet下載檔案的程式碼如下:

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class ExcelServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response){
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        try{
            String path = "D:\\GeoInfoService_List\\GeoInfoService\\web\\file\\template.xls";
            File f = new File(path);
            response.setHeader("Content-disposition", "attachment; filename=output.xls");// 設定輸出檔案頭
            response.setContentType("application/x-msdownload");

            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(f);
            BufferedInputStream bis = new BufferedInputStream(fis);

            byte data[] = new byte[1024];
            int length = -1;
            while((length = bis.read(data)) != -1){
                os.write(data,0,length);
            }
            bis.close();
            os.flush();
            os.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

不要在os上再包一層BufferdOutputStream用它來write,這樣會導致下載的檔案比實際的檔案小,導致檔案流部分丟失,檔案損壞無法開啟。

相關文章