首頁  >  文章  >  Java  >  java下載檔名亂碼解決方法介紹

java下載檔名亂碼解決方法介紹

尚
原創
2019-12-03 10:53:541842瀏覽

java下載檔名亂碼解決方法介紹

java Web開發下載檔案功能(程式碼如下),檔案名稱如果帶有中文,經常會出現亂碼現象,需要編碼。 (建議:java影片教學

String fileName = "测试文件.doc";
try {

    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();

    response.setHeader("Content-disposition", "attachment; filename=" + fileName);

    response.setContentLength((int) file.length());

    response.setContentType("application/octet-stream;charset=UTF-8");

    byte[] b = new byte[1024];

    int i = 0;

    FileInputStream fis = new FileInputStream(file);

    ServletOutputStream out = response.getOutputStream();
    while ((i = fis.read(b)) > 0) {

        out.write(b, 0, i);

    }
    out.flush();
    out.close;

    fis.close();

} catch (IOException e) {

    e.printStackTrace();

}
FacesContext.getCurrentInstance().responseComplete();
return null;

方案一:將檔案名稱編碼為Unicode

fileName = URLEncoder.encode(fileName, "UTF-8");

檔案名稱會轉換為Unicode編碼(測試檔案.doc),在IE瀏覽器下測試正常,但Firefox瀏覽器下測試得到的檔案名稱是沒有解碼的Unicode。

方案二:將檔案名稱編碼為ISO-8859-1

fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

這種方式在IE下和Firefox下均可以得到中文檔案名稱的檔案。但如果檔案名稱中帶有空格,Firefox會從空格處截斷檔案名,需要在編碼之前將檔案名稱中的空格替換成下劃線之類的可見字元。

fileName = new String(fileName.replace(" ", "_").getBytes("UTF-8"), "ISO-8859-1");

方案三:瀏覽器不相容

在Java的web開發中,檔案下載功能的檔案名稱檔案名稱亂碼問題是經常遇到的。

對於這個問題,不同的瀏覽器,解決的方法不太一樣。

IE的話,透過URLEncoder對filename進行UTF8編碼。

而其他的瀏覽器(firefox、chrome、safari、opera),則要透過位元組轉換成ISO8859-1了。

if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
    filename = URLEncoder.encode(filename, "UTF-8");
} else {
    filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
}

更多java知識請關注java基礎教學欄位。

以上是java下載檔名亂碼解決方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn