Http协议(下载)

来源:互联网 发布:学外语的软件 编辑:程序博客网 时间:2024/06/11 23:31
public class DownServlet extends HttpServlet {    @Override    protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {        resp.setContentType("application/force-download");//协议设置1        String fileName = "1.jpg";        InputStream fin = DownServlet.class.getClassLoader().getResourceAsStream(fileName);        fileName = "我的图片.jpg";        fileName = URLEncoder.encode(fileName,"UTF-8");//如果不编码,浏览器中显示的文件名是乱码        resp.setHeader("Content-Disposition","attachment;filename=\""+fileName+"\"");//协议设置2 ---告诉浏览器,当前所下载文件的文件名        //FileInputStream fin = new FileInputStream(fileName);        OutputStream out = resp.getOutputStream();        byte buf[] = new byte[512];        int len=0;        while( (len=fin.read(buf))!=-1){            out.write(buf, 0, len);        }       }}

注意上例中图片1.jpg的存放位置是在src目录下的。

0 0
原创粉丝点击