JAVA文件下載功能問題解決日志


  今天給報告系統做了個下載功能,遇到了挺多問題,通過查資料一一解決了。

1、首先遇到的問題是:java后台的輸出流輸出之后,沒有任何報錯,瀏覽器端不彈出保存文件的對話框,原本是ajax請求到后台的controller方法中添加了下載的方法,type和async兩個參數的四種組合都不行,棄用ajax,用window.location.href='file/download?path='+file;重新發一個新的下載請求之后,保存對話框終於彈出。

2、彈出之后,發現文件名亂碼,后台的解決方案代碼如下:

      private static final String CHARSET = "utf-8";

String agent = request.getHeader("User-Agent").toLowerCase(); if (agent != null && (agent.indexOf("msie") != -1 || (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1))) { fileName = URLEncoder.encode(file.getName(), "UTF-8"); } else { fileName = new String(file.getName().getBytes(CHARSET), "ISO8859-1"); }

3、后台一直在報錯getWriter() has already been called for this response,通過報錯內容大概可以看出ServletOutputStream out = response.getOutputStream();這個應該是個單例的,但是又沒有發現別的地方在調用這個方法獲取輸出流,仔細測試發現,每次把所有的請求全部關閉之后,第一次不會出問題,之后再請求就會報錯,把后面的out.close();注釋掉,報錯就解決了。

4、前台拼文件路徑的方法

                var file;
                var path = $("#lujing").val();
                if(path.lastIndexOf('\\')!=path.length-1){
                    //console.info("不以斜杠結尾");
                    file = $("#lujing").val() + "\\" + $("#city").val() + "市" + $("#year1").val()
                    + $("#month1").val() + "電商數據分析報告.doc";
                } else {
                    //console.info("以斜杠結尾");
                    file = $("#lujing").val() + $("#city").val() + "市" + $("#year1").val()
                    + $("#month1").val() + "電商數據分析報告.doc";
                }
                
                window.location.href='file/download?path='+file;

5、導出controller

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * @author 作者 Jeffy
 * @version 
 * 
 */
@Controller  
public class FileController{
    //Spring這里是通過實現ServletContextAware接口來注入ServletContext對象  

    private static final String CHARSET = "utf-8";
    @RequestMapping("/exportreport/file/download")  
    public static void fileDownload(HttpServletResponse response, HttpServletRequest request,
            String path) throws UnsupportedEncodingException{

        File file = new File(path);
        String fileName;
        String agent = request.getHeader("User-Agent").toLowerCase();
        if (agent != null && (agent.indexOf("msie") != -1 ||   
                (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1))) {
            fileName = URLEncoder.encode(file.getName(), "UTF-8"); 
        } else {  
            fileName = new String(file.getName().getBytes(CHARSET), "ISO8859-1");
        }

//        response.reset(); //非常重要
        //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型
        response.setContentType("multipart/form-data");
        response.setContentType("application/OCTET-STREAM;charset=UTF-8");
        //2.設置文件頭:最后一個參數是設置下載文件名(假如我們叫a.pdf)
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
        ServletOutputStream out;

        try {  
            FileInputStream inputStream = new FileInputStream(file);
  
            //3.通過response獲取ServletOutputStream對象(out)  
            out = response.getOutputStream();  
  
            int b = 0;  
            byte[] buffer = new byte[512];  
            while ((b = inputStream.read(buffer)) != -1){  
                //4.寫到輸出流(out)中  
                out.write(buffer,0,b);  
            }  
            inputStream.close();  
//            out.close();  
//            out.flush();  

        } catch (IOException e) {
            e.printStackTrace();  
        }  
    }  

}

以上便是遇到的java文件下載功能全部問題,可能還有暫時沒有測試出的問題,后續發現問題及時更新,也請大家多多批評指正。


免責聲明!

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



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