Servlet实现文件下载的功能

download.html

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件下载title>
    >">
head>
<body>
<h1>文件下载h1>
<a href="fileDownLoadServlet?name=2.png">点击下载图片a><br/><br/>
<a href="fileDownLoadServlet?name=笔记.pdf">点击下载笔记a><br/><br/>
body>
html>

FileDownLoadServlet

package com.sparrow.servlet;

import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;

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.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @Author: 诉衷情の麻雀
 * @Description: TODO
 * @DateTime: 2023/7/15 12:41
 **/
public class FileDownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("FileDownLoadServlet被调用了");
        //准备下载的文件
        req.setCharacterEncoding("utf-8");
        String downLoadName= req.getParameter("name");
        //3.给HTTP响应,设置响应头Content-Type,就是文件的MiME
        ServletContext servletContext = req.getServletContext();
        String downLoadPath = "/download/";
        String downLoadFileFullPath = downLoadPath + downLoadName;
        String mimeType = servletContext.getMimeType(downLoadFileFullPath);
        resp.setContentType(mimeType);
        //4.给HTTP响应设置响应头Content-Disposition 是指定下载的数据的展示形式
        //如果是attachment则使用文件下载方式
        //如果是Firefox 则中文编码需要 base64
        if (req.getHeader("User-Agent").contains("Firefox")) {
            // 火狐 Base64编码
            resp.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" +
                    new BASE64Encoder().encode(downLoadName.getBytes("UTF-8")) + "?=");
        } else {
            // 其他(主流ie/chrome)使用URL编码操作
            resp.setHeader("Content-Disposition", "attachment; filename=" +
                    URLEncoder.encode(downLoadName, "UTF-8"));
        }
        //5.读取下载的文件数据,返回给客户端/浏览器
        // 1)创建一个和要下载的文件关联的输入流
        InputStream resourceAsStream = servletContext.getResourceAsStream(downLoadFileFullPath);
        //2) 得到返回数据的输出流【因为返回的文件大多是二进制字节】
        ServletOutputStream outputStream = resp.getOutputStream();
        //3)使用工具类,将输入流关联的文件对拷到输出流,并返回给客户端/浏览器
        IOUtils.copy(resourceAsStream, outputStream);
    }



}

在web下建一个目录将要下载的文件放入该项目下

Servlet实现文件下载的功能_第1张图片
## 项目演示

你可能感兴趣的:(JavaWeb,servlet)