//实现文件下载(如果是中文文件名的话,在输出给客户机下载时,要记得url编码)
public class ResponseDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = this.getServletContext().getRealPath("/download/中国人.jpg");
String filename = path.substring(path.lastIndexOf("\\")+1);
//设置下载头信息,如果文件是中文,必须要进行URL编码
response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
FileInputStream in = new FileInputStream(path);
int len = 0;
byte buffer[] = new byte[1024];
OutputStream out = response.getOutputStream();
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
转载于:https://my.oschina.net/u/936286/blog/262164