14-下载案例

2022-10-27 13:20:06 浏览数 (1)

下载案例

HTML文件

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--定义超链接跳转到对应的Servlet并且携带文件名参数-->
<a href="/DownloadTest/downloadServlet?filename=1.jpg">点击下载图片1</a><br>
<a href="/DownloadTest/downloadServlet?filename=2.jpg">点击下载图片2</a><br>
<a href="/DownloadTest/downloadServlet?filename=3.jpg">点击下载图片3</a><br>


</body>
</html>

Servlet

代码语言:javascript复制
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取请求参数(即文件名称)
        String filename=request.getParameter("filename");
        //2. 使用字节输入流加载文件进内存
        //2.1 获取文件真实路径
        String path=this.getServletContext().getRealPath("/img/" filename);  //通过ServletContext对象获取真实路径
        //2.2 加载进内存
        FileInputStream fis=new FileInputStream(path);
        //3. 设置响应头数据
        //3.1 设置content-type(需要利用ServletContext获取文件的MIME类型)
        String mimeType=this.getServletContext().getMimeType(filename);
        response.setHeader("content-type",mimeType);
        //3.2 设置content-disposition(文件的打开方式,以附件形式打开。filename属性表示保存文件的名称)
        response.setHeader("content-disposition","attachment;filename=" filename);
        //4. 将文件内容(输入流)写入输出流中
        ServletOutputStream sos=response.getOutputStream();
        int len=0;
        byte[] buff=new byte[1024*8];
        while((len=fis.read(buff))!=-1){
            sos.write(buff,0,len);
        }
        fis.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

0 人点赞