2021-05-03 10:14  阅读(106)
文章分类:Spring MVC 教程 文章标签:SpringSpring MVC
©  原文作者:一点教程 原文地址:http://www.yiidian.com/springmvc/

刚才讲解了Spring MVC实现文件上传,接着,我们看看Spring MVC如何实现文件下载。

1 准备下载的文件

202105031014132121.png

2 设计下载页面

    
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>一点教程网-文件下载</title>
    </head>
    <body>
    <h3>SpringMVC文件下载</h3>
    <a href="/down">下载</a>
    </body>
    </html>
    

3 编写DownController

    
    package com.yiidian.controller;
    import com.yiidian.domain.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.*;
    import java.util.UUID;
    
    /**
     *  演示Spring MVC文件下载
     * 一点教程网 - www.yiidian.com
     */
    @Controller
    public class DownController {
    
        /**
         * 下载文件
         */
        @RequestMapping("/down")
        public void upload(HttpSession session, HttpServletResponse response) throws Exception {
            //模拟文件下载
            //1.读取需要下载的文件
            InputStream inputStream = session.getServletContext()
                    .getResourceAsStream("/upload/spring.jpg");
    
            //2.输出文件
            //设置响应头
            response.setHeader("Content-Disposition","attachment;filename=spring.jpg");
            OutputStream outputStream = response.getOutputStream();
    
            byte[] buf = new byte[1024];
            int len = 0;
            while( (len = inputStream.read(buf))!=-1 ){
                outputStream.write(buf,0,len);
            }
    
            //3.关闭资源
            outputStream.close();
            inputStream.close();
        }
    }
    

4 运行测试

202105031014133202.png

源码下载:https://pan.baidu.com/s/1mhlmg2IfYYMBgj7Ubs08Sw

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> Spring MVC 文件下载
上一篇
Spring MVC 文件上传
下一篇
Spring MVC 拦截器