1. 程式人生 > >SSM專案 JSP頁面中超連結含中文檔名,無法下載的問題解決

SSM專案 JSP頁面中超連結含中文檔名,無法下載的問題解決

兩種解決方案:

一、修改Tomcat配置檔案 

在server.xml檔案 ,找到如下程式碼

    <Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
在 />前加URIEncoding="UTF-8"即可
<Connector port="8080" protocol="HTTP/1.1"   
               connectionTimeout="20000"   
               redirectPort="8443"  URIEncoding="UTF-8"  />

但這樣做有一個弊端,之前後臺程式碼涉及到字元轉換的都會出問題,

比如new String(fileName.getBytes("ISO-8859-1"),"utf-8");

二、後臺程式碼通過字元流的形式處理

前臺程式碼如下:

<a class="btn btn-small btn-success" href="manager/test/download.html?fileName=基本工資.xls" >基本工資表模板下載</a>

後臺程式碼如下:
	@RequestMapping(value = "/download")
	public void download(String fileName, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);// filename iso-8859-1格式

		String downloadName = new String(fileName.getBytes("ISO-8859-1"),
				"utf-8");// 轉換為utf-8格式 file路徑才可以找到
		InputStream inputStream = null;
		OutputStream outputStream = null;
		String path = request.getServletContext().getRealPath("file/app");
		byte[] bytes = new byte[2048];
		try {
			File file = new File(path, downloadName);
			inputStream = new FileInputStream(file);
			outputStream = response.getOutputStream();
			int length;
			// inputStream.read(bytes)從file中讀取資料,-1是讀取完的標誌
			while ((length = inputStream.read(bytes)) > 0) {
				// 寫資料
				outputStream.write(bytes, 0, length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 關閉輸入輸出流
			if (outputStream != null) {
				outputStream.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}

如果涉及到中文名的檔案下載建議大家使用第二種,儘量不要去修改預設的伺服器配置檔案!