天天看点

MultipartResolver实现文件下载

首先在首页添加下载文件的功能选项:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
<title>初始页面</title>
</head>
<body>

<h3>
  <a href="${pageContext.request.contextPath}/Log/gologin">登录页面</a>
</h3>
<h3>
<a href="${pageContext.request.contextPath}/Log/main">进入首页</a>
</h3>
<h3>
  <a href="${pageContext.request.contextPath}/Upload/goinput">文件上传</a>
</h3>
<h3>
  <a href="${pageContext.request.contextPath}/Upload/godownload">文件下载</a>
</h3>
</body>
</html>
           

然后在Controller中写请求:

//跳转到下载文件界面
    @RequestMapping("/godownload")
    public String godownloads(){
        return "download";
    }
           
//下载文件
    @RequestMapping("/download")
    public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
        //要下载的图片地址
        String path = request.getServletContext().getRealPath("input");
        String fileName = "Java开发学习路线.png";

        //设置response响应头
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        //设置响应头
        response.setHeader("Content-Disposition","attachment;fileName="+
                    URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        File file = new File(path,fileName);
        //读取文件-输出流
        InputStream inputStream = new FileInputStream(file);
        //写文件-输出流
        OutputStream outputStream = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        //执行写出操作
        while ((index=inputStream.read(buff))!=-1){
            outputStream.write(buff,0,index);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
        return "downloadSuccess";
    }
           

规定了要下载文件的路径以及文件名,更换要下载的文件只需要改动这部分即可。

然后写发送下载请求的页面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: shadowpee
  Date: 2021/1/25
  Time: 23:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/Upload/download">下载图片</a>
<a href="${pageContext.request.contextPath}">回到首页</a>

</body>
</html>

           

打开Tomcat服务器试验一下:

MultipartResolver实现文件下载

点击文件下载,跳转到下载文件界面

MultipartResolver实现文件下载

点击发送下载请求:

MultipartResolver实现文件下载

下载成功,回到首页。

上一篇: Java复习回顾