1.英文参数的下载
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1 获得要下载的名称
String fname=request.getParameter("filename");
// 2.修改头
response.setContentType(this.getServletContext().getMimeType(fname));
// 3.告诉客户端不要解析
response.setHeader("Content-Disposition", "attachment;filename="+fname);
// 4.获得文件的绝对路径
String url=this.getServletContext().getRealPath("download/"+fname);
// 5.获得两个流
ServletOutputStream out=response.getOutputStream();
InputStream in=new FileInputStream(url);
// 6.加载文件
int len=0;
byte[] buf=new byte[1024];
while((len=in.read(buf))!=-1) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
2.中文参数的下载
public class DownloadServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1 获得要下载的名称
String fname = request.getParameter("filename");
// 编码 变成 美女.jpg
fname = new String(fname.getBytes("ISO8859-1"), "UTF-8");
String agent = request.getHeader("User-Agent");
// 解码都的变量 ????.jpg
String fnameEnc = "";
// 浏览器辨别
if (agent.contains("MSIE")) {
// IE浏览器
fnameEnc = URLEncoder.encode(fname, "utf-8");
fnameEnc = fname.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
fnameEnc = "=?utf-8?B?" + base64Encoder.encode(fname.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
fnameEnc = URLEncoder.encode(fname, "utf-8");
}
// 2.修改头
response.setContentType(this.getServletContext().getMimeType(fname));
// 3.告诉客户端不要解析
response.setHeader("Content-Disposition", "attachment;filename=" + fnameEnc);
// 4.获得文件的绝对路径
String url = this.getServletContext().getRealPath("download/" + fname);
// 5.获得两个流
ServletOutputStream out = response.getOutputStream();
InputStream in = new FileInputStream(url);
// 6.加载文件
int len = 0;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
}