文件下载

文件下载

package org.example.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 FileServletDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //要获取下载文件的路径
        String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/风景.webp");
        System.out.println("下载文件的路径: "+realPath);
        //获取下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf('\\') + 1);
        //设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西
        resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"utf-8"));
        //获取下载文件的输入流
        FileInputStream fileInputStream = new FileInputStream(realPath);
        //创建缓冲区
        int len=0;
        byte[] buffer=new byte[1024];
        //获取OutputStream对象
        ServletOutputStream outputStream = resp.getOutputStream();
        //将OutputStream写入到buffer缓冲区
        while((len=fileInputStream.read(buffer))>0){
            outputStream.write(buffer,0,len);
        }
        outputStream.close();
        fileInputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
上一篇:通过Servlet下载文件(学习笔记)


下一篇:servlet学习笔记3---文件下载