使用response.setHeader(“Content-Disposition”,”attachment;filename=”+fName)下載文件,
中文文件名無法顯示的問題及空格處理
**該問題解決重點在於這兩塊代碼**
//處理文件名有中文問題
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
file_name= URLEncoder.encode(fileName,"UTF-8");
} else {
file_name= new String(fileName.getBytes(),"ISO-8859-1");
}
//最後加雙引號處理名稱中間有空格問題
response.setHeader("Content-Disposition","attachment;filename=\""+file_name+"\"");
代碼如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author ZhouMengShun
*/
@Controller
@RequestMapping("/demo")
public class DemoController {
@RequestMapping(value = "download", method = RequestMethod.GET)
public void downloadFile(HttpServletRequest request,HttpServletResponse response) {
InputStream in = null;
try {
String fileName="測試文件.rar";//文件名稱
File file = new File("c://"+fileName);//創建文件對象,假設該文件已存在,這裏不做判斷
// 1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型
response.setContentType("application/x-msdownload");
//response.setContentType("multipart/form-data");//也可以這樣寫
String file_name=null;
//處理文件名有中文問題
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
file_name= URLEncoder.encode(fileName,"UTF-8");
} else {
file_name= new String(fileName.getBytes(),"ISO-8859-1");
}
//最後加雙引號處理名稱中間有空格問題
response.setHeader("Content-Disposition","attachment;filename=\""+file_name+"\"");
in = new FileInputStream(file);
// 3.通過response獲取ServletOutputStream對象(out)
int b = 0;
byte[] buffer = new byte[512];
while (b != -1) {
b = in.read(buffer);
if (b != -1) {
response.getOutputStream().write(buffer, 0, b);// 4.寫到輸出流(out)中
}
}
} catch (Exception e) {
} finally {
try {
if (in != null) {
in.close();
}
response.getOutputStream().flush();
} catch (Exception ex) {
}
}
}
}