使用response实现文件下载功能
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
//获取绝对路径.通过ervletContext()
String path= this.getServletContext().getRealPath("/img/1.jpg");
//设置请求的头信息,第一参数:头的名称,第二参数:头值,URLEncoder.encode()转编码值
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(path.substring(path.lastIndexOf("\\")+1),"utf-8") );
FileInputStream in=new FileInputStream(path);
byte[] img=new byte[1024];
int length=0;
try {
while ((length=in.read(img, 0, img.length))!=-1) {
response.getOutputStream().write(img, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
in.close();
}