A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 这个好吃给你吃 初级黑马   /  2019-5-9 13:48  /  681 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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);
    }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马