Servlet学习笔记---下载图片

来源:互联网 发布:淘宝运营团队分工 编辑:程序博客网 时间:2024/06/11 17:07

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String path = this.getServletContext().getRealPath("/架构师之路.jpg");String name=path.substring(path.lastIndexOf("\\")+1);response.setHeader("content-disposition", "attachment ; filename="+URLEncoder.encode(name,"UTF-8"));OutputStream out = response.getOutputStream();FileInputStream file=new FileInputStream(new File(path));byte[]b=new byte[1024];int len=0;while((len=file.read(b))>0){out.write(b,0,len);}out.close();file.close();}

就是这样写的,需要注意两个问题。

1.若名称是中文,则要设置URLEncode.encode(string,"UTF-8")来解析汉字。

2.response.setHeader("content-disposition"  ,  "attachment ; filename="+name);







0 0
原创粉丝点击