• SpringMVC作用域传递及文件上传下载功能


    1 SpringMVC作用域传递

    名称说明
    page当前页面有效【当前jsp页面内有效】
    request当前请求中有效
    session当前会话中有效【浏览器不关闭,session不失效的情况下】
    application所有应用程序中有效

    1.1 传统方式

    测试:
    TestScopeController:

    package com.zi.controller;
    
    import com.zi.pojo.User;
    import com.zi.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import java.util.List;
    
    @Controller
    public class TestScopeController {
        @Autowired
        private UserService userService;
    
        @RequestMapping("/testScope")
        public String testScope(HttpServletRequest request, HttpSession session){
            ServletContext application = request.getServletContext();
            List<User> users = userService.findAllUser();
            request.setAttribute("users", users);
            session.setAttribute("users", users);
            application.setAttribute("users", users);
            return "showData";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    showData.jsp:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    
        Title
    
    
    【request】:${requestScope.users[0].uname}
    【session】:${sessionScope.users[0].uname}
    【application】:${applicationScope.users[0].uname}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    1.2 SpringMVC方式

    1.2.1 使用Model

    /**
         * model对象主要是针对请求域传递数据进行了API上的封装【request】
         * model中的字符串类型的键值对信息会转换为请求参数,转发给目标组件
         * @param model
         * @return
         */
        @RequestMapping("/testScope2")
        public String testScope2(Model model){
            List<User> users = userService.findAllUser();
            model.addAttribute("users", users);
            return "showData";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    1.2.2 使用ModelAndView

    /**
         * Model 数据
         * View 视图
         * @return
         */
        @RequestMapping("/testScope3")
        public ModelAndView testScope3(){
            ModelAndView mv = new ModelAndView();
            Map<String, Object> model = mv.getModel();
            List<User> users = userService.findAllUser();
            model.put("users", users);
            mv.setViewName("forward:/showData.jsp");
            return mv;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2 文件上传下载

    2.1 文件上传

    控制文件类型:

    //控制文件格式:只能上传.png
    if(!extendsName.equals(".png")){
        map.put("message", "文件格式只能为.png");
        return map;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    控制文件大小:

    //控制文件上传大小 不能超过400kb
    long size = headPhoto.getSize();
    if(size > 1024*400){
        map.put("message", "文件大小不能超过400kb");
        return map;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    图片回显:
    【注意在springmvc中配置静态资源放行】

    <mvc:resources mapping="/upload/**" location="/upload/">
    
    • 1

    整个代码:
    login.jsp:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>注册页面title>
        <script src="js/jquery-3.4.1.js">script>
        <style>
            .progress {
                width: 200px;
                height: 10px;
                border: 1px solid #ccc;
                border-radius: 10px;
                margin: 10px 0px;
                overflow: hidden;
            }
    
            /* 初始状态设置进度条宽度为0px */
            .progress > div {
                width: 0px;
                height: 100%;
                background-color: yellowgreen;
                transition: all .3s ease;
            }
    
        style>
        <script>
            $(function () {
                $("#uploadFile").click(function () {
                    //获取要上传的文件
                    var photoFile = $("#photo")[0].files[0]
                    if (photoFile == undefined) {
                        alert("您还未选中文件");
                        return;
                    }
                    //将文件装入FormData对象
                    var formData = new FormData();
                    formData.append("headPhoto", photoFile);
                    //ajax向后台发送图像
                    $.ajax({
                        type: "post",
                        data: formData,
                        url: "fileUpload",
                        processData: false,
                        contentType: false,
                        success: function (result) {
                            //接收后台的响应
                            // alert(result.message);
                            console.log(result)
                            //图片回显
                            $("#headImg").attr("src","upload/" + result.newFileName);
                        },
                        xhr: function () {
                            var xhr = new XMLHttpRequest();
                            //使用XMLHttpRequest.upload监听上传过程,
                            // 注册progress事件,打印回调函数中的event事件
                            xhr.upload.addEventListener('progress',
                                function (e) {
                                    //loaded代表上传了多少
                                    //total代表总数为多少
                                    var progressRate = (e.loaded / e.total)
                                        * 100 + '%';
                                    //通过设置进度条的宽度达到效果
                                    $('.progress > div').css('width',
                                        progressRate);
                                })
    
                            return xhr;
                        }
                    })
    
                })
            })
        script>
    head>
    <body>
    <form action="addPlayer" method="post">
        账号:<input type="text" name="name"><br/>
        密码:<input type="password" name="password"><br/>
        昵称:<input type="text" name="nickname"><br/>
        头像:
        <input id="photo" type="file" name="filetype"><br/>
        <%--图片回显--%>
        <img id="headImg" style="width: 200px;height: 100px" alt="你还未上传图片"/>
        <%--进度条设置--%>
        <div class="progress">
            <div>div>
        div>
        <a id="uploadFile" href="javascript:void(0)">立即上传a>
        <input type="submit" value="注册">
    
    form>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93

    FileUploadController:

    package com.zi.controller;
    
    import org.springframework.stereotype.Controller;
    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 java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;
    
    @Controller
    public class FileUploadController{
    
        @ResponseBody
        @RequestMapping("/fileUpload")
        public Map<String, String> fileUpload(MultipartFile headPhoto, HttpServletRequest request) throws IOException {
            Map<String, String> map = new HashMap<>();
            //控制文件上传大小 不能超过400kb
            long size = headPhoto.getSize();
            if(size > 1024*400){
                map.put("message", "文件大小不能超过400kb");
                return map;
            }
            //指定文件目录为项目部署环境下的upload目录
            String realPath = request.getServletContext().getRealPath("/upload");
            File dir = new File(realPath);
            //如果不存在则创建目录
            if(!dir.exists()){
                dir.mkdirs();
            }
            //获取文件名
            String originalFilename = headPhoto.getOriginalFilename();
            //为了避免文件名冲突,使用UUID替换文件名
            String uuid = UUID.randomUUID().toString();
            //获取文件拓展名
            String extendsName = originalFilename.substring(originalFilename.lastIndexOf("."));
    
            //控制文件格式:只能上传.png
            if(!extendsName.equals(".png")){
                map.put("message", "文件格式只能为.png");
                return map;
            }
            //新的文件名
            String newFileName = uuid.concat(extendsName);
            //文件存储位置
            File file = new File(dir, newFileName);
            //文件保存
            headPhoto.transferTo(file);
            map.put("message", "文件上传成功");
            map.put("fileType", headPhoto.getContentType());
            map.put("newFileName", newFileName);
            return map;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59

    测试结果;
    在这里插入图片描述

    拓展:单独使用tomcat作为一台文件服务器

    PlayerController:

    @Controller
    public class PlayerController {
        private static final String FILESERVER = "http://192.168.145.1:8090/upload/";
    
        @ResponseBody
        @RequestMapping("/fileUpload")
        public Map<String, String> addPlayer(MultipartFile headPhoto, HttpServletRequest request) throws IOException {
            Map<String, String> map = new HashMap<>();
            //获取文件名
            String originalFilename = headPhoto.getOriginalFilename();
            //为了避免文件名冲突,使用UUID替换文件名
            String uuid = UUID.randomUUID().toString();
            //获取文件拓展名
            String extendsName = originalFilename.substring(originalFilename.lastIndexOf("."));
    
            //新的文件名
            String newFileName = uuid.concat(extendsName);
            //创建sun公司提供的jersey包中的client对象
            Client client = Client.create();
            WebResource resource = client.resource(FILESERVER + newFileName);
            //文件保存到另一台tomcat上
            resource.put(String.class, headPhoto.getBytes());
            map.put("message", "文件上传成功");
            map.put("fileType", headPhoto.getContentType());
            map.put("newFileName", newFileName);
            return map;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    login.jsp:

    //图片回显
    $("#headImg").attr("src","http://192.168.145.1:8090/upload/"+result.newFileName);
    
    • 1
    • 2

    将用户数据注册到数据库:
    PlayerController:

    @Controller
    public class PlayerController {
        @Autowired
        private PlayerService playerService;
    
        @RequestMapping("/addPlayer")
        public String addPlayer(Player player){
            playerService.addPlayer(player);
            return "redirect:/html/showPlayer.html";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    login.jsp:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>注册页面</title>
        <script src="js/jquery-3.4.1.js"></script>
        <style>
            .progress {
                width: 200px;
                height: 10px;
                border: 1px solid #ccc;
                border-radius: 10px;
                margin: 10px 0px;
                overflow: hidden;
            }
    
            /* 初始状态设置进度条宽度为0px */
            .progress > div {
                width: 0px;
                height: 100%;
                background-color: yellowgreen;
                transition: all .3s ease;
            }
    
        </style>
        <script>
            $(function () {
                $("#uploadFile").click(function () {
                    //获取要上传的文件
                    var photoFile = $("#photo")[0].files[0]
                    if (photoFile == undefined) {
                        alert("您还未选中文件");
                        return;
                    }
                    //将文件装入FormData对象
                    var formData = new FormData();
                    formData.append("headPhoto", photoFile);
                    //ajax向后台发送图像
                    $.ajax({
                        type: "post",
                        data: formData,
                        url: "fileUpload",
                        processData: false,
                        contentType: false,
                        success: function (result) {
                            //接收后台的响应
                            // alert(result.message);
                            console.log(result)
                            //图片回显
                            $("#headImg").attr("src","http://192.168.145.1:8090/upload/"+result.newFileName);
                            //将文件类型和文件名放入form表单
                            $("#photoInput").val(result.newFileName)
                            // alert(result.newFileName);
                            // alert(result.filetype);
                            $("#filetypeInput").val(result.filetype)
                        },
                        xhr: function () {
                            var xhr = new XMLHttpRequest();
                            //使用XMLHttpRequest.upload监听上传过程,
                            // 注册progress事件,打印回调函数中的event事件
                            xhr.upload.addEventListener('progress',
                                function (e) {
                                    //loaded代表上传了多少
                                    //total代表总数为多少
                                    var progressRate = (e.loaded / e.total)
                                        * 100 + '%';
                                    //通过设置进度条的宽度达到效果
                                    $('.progress > div').css('width',
                                        progressRate);
                                })
    
                            return xhr;
                        }
                    })
    
                })
            })
        </script>
    </head>
    <body>
    <form action="addPlayer" method="post">
        账号:<input type="text" name="name"><br/>
        密码:<input type="password" name="password"><br/>
        昵称:<input type="text" name="nickname"><br/>
        头像:
        <input id="photo" type="file" name="filetype"><br/>
        <%--图片回显--%>
        <img id="headImg" style="width: 200px;height: 100px" alt="你还未上传图片"/>
        <%--进度条设置--%>
        <div class="progress">
            <div></div>
        </div>
        <a id="uploadFile" href="javascript:void(0)">立即上传</a>
        <input type="submit" value="注册">
        <input type="hidden" id="photoInput" name="photo">
        <input type="hidden" id="filetypeInput" name="filetype">
    
    </form>
    </body>
    </html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100

    2.2 文件回显与下载

    showPlayer.jsp:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
        <style>
            #playerTable{
                width: 50%;
                border: 3px solid sienna;
                margin: 0px auto;
                text-align: center;
            }
            #playerTable th, td{
                border: 1px solid goldenrod;
            }
            #playerTable img{
                width: 100px;
                height: 100px;
            }
        </style>
        <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
        <script>
            $(function(){
                $.ajax({
                    type:"get",
                    url:"getAllPlayer",
                    success:function (players){
                        $.each(players, function (i, e){//i表示是第几个 e是代表单个player
                            $("#playerTable").append('\n' +
                                '        '+e.id+'\n' +
                                '        '+e.name+'\n' +
                                '        '+e.password+'\n'
                                +
                                '        '+e.nickname+'\n'
                                +
                                '        \n' +
                                '            +e.photo+'" alt=""  src>\n' +
                            '        \n' +
                            '        \n' +
                            '            +e.photo+'&filetype='+e.filetype+'">下载\n'
                            +
                            '        \n' +
                            '    ')
    
                        })
                    }
                })
            })
    
        </script>
    </head>
    <body>
    
    <table id="playerTable" cellspacing="0px" cellpadding="0px">
        <tr>
            <th>编号</th>
            <th>用户名</th>
            <th>密码</th>
            <th>昵称</th>
            <th>头像</th>
            <th>操作</th>
        </tr>
    </table>
    </body>
    </html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    playerController.java:

    package com.zi.controller;
    
    import com.zi.pojo.Player;
    import com.zi.service.PlayerService;
    import org.apache.commons.io.IOUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.util.List;
    
    @Controller
    public class PlayerController {
    
        private static final String FILESERVER = "http://192.168.145.1:8090/upload/";
    
        @Autowired
        private PlayerService playerService;
    
        @RequestMapping("/addPlayer")
        public String addPlayer(Player player){
            playerService.addPlayer(player);
            return "redirect:/html/showPlayer.html";
        }
    
        @RequestMapping("/getAllPlayer")
        @ResponseBody
        public List<Player> getAllPlayer(){
            System.out.println("--------------");
            return playerService.getAll();
        }
    
        @RequestMapping("/fileDownload")
        public void fileDownload(String photo, String filetype, HttpServletResponse response) throws IOException {
            //设置响应头
            //告知浏览器要将数据保存在磁盘上,不在浏览器上直接解析
            response.setHeader("Content-Disposition", "attachment;filename="+photo);
            //告诉浏览器下载的文件类型
            response.setContentType(filetype);
            //获取一个文件的输入流
            InputStream inputStream = new URL(FILESERVER + photo).openStream();
            //获取一个指向浏览器的输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //向浏览器响应文件
            IOUtils.copy(inputStream, outputStream);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

    效果展示:
    在这里插入图片描述

    在这里插入图片描述

  • 相关阅读:
    CSS 设置垂直居中
    闪迪ssd plus固态硬盘不识别开卡成功,慧荣SM2246XT量产教程
    为什么说Java不适合做游戏开发,劣势在哪里?
    景联文科技:数据供应商在新一轮AI热潮中的重要性
    超详细的三星全系列机型线刷图文教程和相关注意操作常识 二
    掌握Java中的volatile关键字
    数据库临时表(Temporary Table)
    力扣:递增子序列java
    LayaBox---TypeScript---JavaScript文件类型检查
    微信小程序通过npm引入tdesign包进行构建的时候报错
  • 原文地址:https://blog.csdn.net/weixin_45565886/article/details/125948780