黑马程序员技术交流社区

标题: download servlet [打印本页]

作者: 这个好吃给你吃    时间: 2019-5-9 13:48
标题: download servlet
package cn.itcast.servlet;

import cn.itcast.utils.DownLoadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

@WebServlet("/dkservlet")
public class dkservlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取文件名称
        String filename = request.getParameter("filename");
        //2. 使用字节输入流加载文件进内存
        ServletContext servletContext = this.getServletContext();

        String realPath = servletContext.getRealPath("/img/"+filename);
        FileInputStream fis = new FileInputStream(realPath);
        System.out.println(realPath);

        //3. 指定response的响应头: content-disposition:attachment;filename=xxx
        String mp = servletContext.getMimeType(filename);
        //3.1 制定响应头对应的浏览器解析的content-Type
        response.setHeader("content-Type",mp);
        //3.1.1 解决中文乱码问题
        String agent = request.getHeader("user-agent");
        //3.1.2 调用工具类
        filename = DownLoadUtils.getFileName(agent, filename);
        //3.2 设置响应头
        response.setHeader("content-disposition","attachment;filename="+filename);

        //4.将数据写出到response输出流
        ServletOutputStream sos = response.getOutputStream();

        byte[] bs = new byte[1024 * 8];

        int len = 0;
        while ((len = fis.read(bs))!= -1 ){
            sos.write(bs,0,len);
        }
        fis.close();


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2