中文文件下載
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號: 73203。
假如你的文件名是英文的話,jspsmartupload就可以勝任。但如果你的文件名是中文的話,就只能用下面的方法。這時jspsmartupload 是不能勝任的。以下例子能下載中文文件名(在firefox,ie8,360都通過測試, eclipse內(nèi)置瀏覽器不行):
例 1.2.1
<%@ page contentType="text/html; charset=GBK" %>
<html>
<body >
<A href="http://localhost:8080/ServletHello/MarkToWinServlet?file=ibatis環(huán)境搭建.ppt">下 載ibatis環(huán)境搭建.ppt</A>
</body>
</html>
package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException {
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
try {
String filenameiso = request.getParameter("file");
System.out.println("filenameiso is " + filenameiso);
String filenamegbk = new String(filenameiso.getBytes("iso8859-1"), "GBK");
System.out.println("filenameutf is " + filenamegbk);
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment; filename="
+ filenameiso);
System.out.println("after setHeader");
bis = new java.io.BufferedInputStream(new java.io.FileInputStream(
getServletContext().getRealPath("file/" + filenamegbk)));
bos = new java.io.BufferedOutputStream(response.getOutputStream());
System.out.println("after new bis bos ");
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
System.out.println("after while ");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
System.out.println("finish ");
}
}
馬克-to-win:網(wǎng)上傳來的數(shù)據(jù)是iso編碼的,所以我再把已經(jīng)正確的數(shù)據(jù)傳回去setHeader("Content-disposition", "attachment; filename=" + filenameiso);(雖然filenameiso,我們?nèi)搜劭床欢?,機(jī)器卻能接受)。通過觀察整個輸出發(fā)現(xiàn),當(dāng)彈出對話框時,火狐和360瀏覽器已經(jīng)把文件傳到客戶端了。存在一個緩存的地方。即使你可能在對話框選擇取消。那樣就浪費(fèi)流量了。而ie就編的非常精細(xì),出現(xiàn)對話框時,程序不往客戶端寫任何東西,只有你真正確認(rèn)存時,才真正向客戶端寫數(shù)據(jù)。這細(xì)節(jié)才看出,ie的技術(shù)確實(shí)比較好。