zoukankan      html  css  js  c++  java
  • 文件下载

    public class DownLoadServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println(1234567890);
            //获取资源的路径
    //        String realPath = this.getServletContext().getRealPath("/1.png");
            String realPath = "E:\Intellij\我的项目 集合\responsedownload\target\classes\1.png";
            //获取资源名称
            String fileName = realPath.substring(realPath.lastIndexOf("/") + 1);
            //fileName = "1.png";
            //设置下载的头
            //resp.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
            resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
            //获取下载文件的输入流
            FileInputStream in = new FileInputStream(realPath);
            int len = 0;
            //缓存区
            byte[] buffer = new byte[1024];
            //获取Output的Stream流
            ServletOutputStream out = resp.getOutputStream();
            while((len = in.read(buffer))>0){
                out.write(buffer,0,len);
            }
            //关闭流
            out.close();
            in.close();
        }
    }

    配置servlet

    <servlet>
        <servlet-name>download</servlet-name>
        <servlet-class>com.cai.servlet.DownLoadServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>download</servlet-name>
        <url-pattern>/down</url-pattern>
      </servlet-mapping>
  • 相关阅读:
    BFC
    js常用
    uploadify上传文件
    android初探
    springMVC
    java虚拟机
    java编程思想
    eclipse中创建maven项目
    struts2、spring和mybatis整合理解
    struts,spring和mybatis框架整合
  • 原文地址:https://www.cnblogs.com/Difcipo/p/14038972.html
Copyright © 2011-2022 走看看