Response下载文件

/ java / 90浏览
  1. 要获取下载文件的路径
  2. 下载的文件名是啥
  3. 设置想办法让浏览器能够支持下载我们的东西
    这里出现了点问题: resp.setHeader("Content-Disposition","attachment;fileName="+fileName); 第一次写的时候少了“=”号
  4. 获取下载文件的输入流
  5. 创建缓冲区
  6. 获取OutputStream对象
  7. 将FileOutStream流写入到buffer缓冲区
  8. 使用OutputSteam将缓冲去中的数据输出到客户端

代码:qq

package top.lhhstudy.servlet;


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.URLEncoder;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //  1. 要获取下载文件的路径
        String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/梁宏华.png");
        System.out.println("文件下载的路径"+realPath);
        //  2. 下载的文件名是啥
        String fileName = realPath.substring(realPath.lastIndexOf("\\" )+ 1);
        System.out.println(fileName);
        //  3. 设置想办法让浏览器能够支持下载我们的东西
        resp.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));
        //  4. 获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        //  5. 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //  6. 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //  7. 将FileOutStream流写入到buffer缓冲区,使用OutputSteam将缓冲去中的数据输出到客户端
        while((len=in.read(buffer)) > 0){
            out.write(buffer,0,len);
        }
        //  8.关闭资源流
        in.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">
        <servlet>
            <servlet-name>fileServlet</servlet-name>
            <servlet-class>top.lhhstudy.servlet.FileServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>fileServlet</servlet-name>
            <url-pattern>/fileServlet</url-pattern>
        </servlet-mapping>
</web-app>

下载结果

image-20220412225641829

站长统计代码