java IO流下載.xlsx .docx 文件時報文件損壞的錯誤修復

由於用IO流下載.xlsx .docx 文件時報文件損壞的錯誤修復,找了半天原因,終於解決了,記錄一下原因,以及解決方案
一.出現損壞的原因:
並不是每次都能讀到1024個字節,所有用len作爲每次讀取數據的長度,否則會出現文件損壞的錯誤

二.解決方法(注意紅的部分代碼)
1.原本文件下載代碼如下:
public void Downloads(HttpServletResponse response , String url){
    try {

        File file = new File(url);
        String str = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String name=str+".xlsx";
        if(file.exists()){ //判斷文件父目錄是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8"));
            response.setHeader("Pragma", URLEncoder.encode(name, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件輸入流
            BufferedInputStream bis = null;
            OutputStream os = null; //輸出流
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            while(bis.read(buffer) != -1){
                os.write(buffer);
            }
            bis.close();
            fis.close();
        }
    }catch (Exception e){
        e.printStackTrace();
        logger.warn("sys:zydownload:Downloads--userId:"+ ShiroUtils.getUserId()+"===="+e.getMessage());
    }
}
注:這種寫法會出現IO流下載.xlsx .docx 文件時報文件損壞的錯誤修復,改成下面的寫法則可以解決

2.改進後的代碼

public void Downloads(HttpServletResponse response , String url){
    try {
        File file = new File(url);
        String str = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String name=str+".xlsx";
        if(file.exists()){ //判斷文件父目錄是否存在
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8"));
            response.setHeader("Pragma", URLEncoder.encode(name, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件輸入流
            BufferedInputStream bis = null;
            OutputStream os = null; //輸出流
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);

            int len = 0;
            while((len = bis.read(buffer)) >0){
                os.write(buffer, 0, len);
            }
            bis.close();
            fis.close();
        }
    }catch (Exception e){
        e.printStackTrace();
        logger.warn("sys:zydownload:Downloads--userId:"+ ShiroUtils.getUserId()+"===="+e.getMessage());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章