欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet实现简单的下载图片

程序员文章站 2022-05-24 14:35:09
...
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.io.OutputStream;

public class DownLoadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取文件下载路径
        String realPath = "C:\\Users\\37407\\Desktop\\beauty.jpg";
        System.out.println(realPath);//检查路径是否正确

        //2.设置文件名称
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        System.out.println(fileName);

        //3.设置响应头浏览器支持我们进行下载(不需要记,百度即可),注意最后文件名字的修改
        resp.setHeader("Content-Disposition","attachment;filename=" + fileName);

        //4.获取输入流
        FileInputStream fileInputStream = new FileInputStream(realPath);

        //5.创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];

        //6.创建输出流,这里用到了response响应
        ServletOutputStream outputStream = resp.getOutputStream();

        //7.将输入流读入缓存区,并输出
        while((len = fileInputStream.read(buffer)) != -1){
            //将缓冲区中的流读出来
            outputStream.write(buffer,0,len);
        }
    }
}

相关标签: Servlet