通过Servlet下载文件(学习笔记)

package com.lhh.Servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URLEncoder;

public class FileServlet extends HttpServlet {
/*  正常实现的时候调用super报错
  @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取下载文件路径
        String realPath = "D:\\Users\\lhh\\IdeaProjects\\javaweb-001-servlet\\response\\target\\classes\\1.png";
        System.out.println("下载的文件路径"+realPath);
        //下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //让浏览器支持下载需要的东西
        resp.setHeader("Content-Disposition","attachment;filename="+fileName);
        //获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        //创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //获取输出流OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //将fileoutputstream流写入到buffer缓冲区,使用outputstream将缓冲区的数据输出到客户端
        while ((len = in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();

    }

 */

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realPath = "D:\\Users\\lhh\\IdeaProjects\\javaweb-001-servlet\\response\\target\\classes\\1.png";
        System.out.println("下载的文件路径"+realPath);
        //下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 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];
        //获取输出流OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //将fileoutputstream流写入到buffer缓冲区,使用outputstream将缓冲区的数据输出到客户端
        while ((len = in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();

    }
}

上一篇:【无标题】


下一篇:文件下载