springboot实现文件的上传下载

SpringBoot文件上传与下载

文件的上传与下载

在springmvc阶段要实现文件的上传下载,需要的依赖—>>

 
    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.4version>
    dependency>
    <dependency>
      <groupId>commons-iogroupId>
      <artifactId>commons-ioartifactId>
      <version>2.8.0version>
    dependency>

在springboot中其实自带了一下关于文件上传和下载的依赖

    package com.gavin.fileupload;
       import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    /**
     * @author Gavin
     */
    @SpringBootApplication
    public class FileuploadApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(FileuploadApplication.class, args);
            String[] beanDefinitionNames = context.getBeanDefinitionNames();
            for (String name : beanDefinitionNames) {
                System.out.println(name);
            }
        }
    
    }

运行结果—>>>

org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
    multipartConfigElement
    multipartResolver
    spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties
    org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$RestartConfiguration
    restartingClassPathChangedEventListener
    classPathFileSystemWatcher
    classPathRestartStrategy
    fileSystemWatcherFactory

所以我们就不需要在引入文件上传组件—multipartResolver
springboot实现文件的上传

1,准备一个服务器,用于存放上传的文件;
springboot实现文件的上传下载_第1张图片
修改端口号和修改只读为false;

启动文件服务器
在这里插入图片描述
跨服务器上传/下载的依赖

先搭建一个框架—>>

登录页–>

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登录页面title>
      <link rel="stylesheet" href="css/fileCss.css" type="text/css"/>
    head>
    <body>
    <div class="main">
        <h2>欢迎访问学生管理系统h2>
        <form action="login.do" method="post" class="form">
            账号: <input type="text", name="name"/>br>
            密码: <input type="password", name="pwd"/>br>
            <button type="submit">登录button><br> <button><a href="registPage.html"><span style="color: white; ">注册span> a>button><br>
        form>
    div>
    body>
    html>

注册页代码

    DOCTYPE html>
    <html lang="en">
    <meta charset="UTF-8">
    <head>
        <title>注册页title>
        <link rel="stylesheet" href="css/login.css">
        <link rel="stylesheet" href="css/font-awesome.css">
        <script type="text/javascript"
                src="js/jquery-3.5.1.min.js">
        script>
        <style>
            input::-webkit-input-placeholder {
                color: white;
            }
    
            input::-moz-placeholder {
                /* mozilla Firefox 19+ */
                color: white;
            }
    
            input:-moz-placeholder {
                /* mozilla Firefox 4 to 18 */
                color: white;
            }
    
            input:-ms-input-placeholder {
                /* Internet Explorer 10-11 */
                color: white;
            }
    
            /*给进度条君添加一些样式*/
    
            .progress {
                width: 400px;
                height: 10px;
                border-radius: 10px;
                margin: 10px 0px;
                overflow: hidden;
            }
    
            .progress > div {
                width: 0px;
                height: 100px;
                background-color: yellowgreen;
                transition: all .3s ease;
            }
    
        style>
    head>
    
    <body>
    <form action="addUser.do" method="POST">
        <div id="login-box">
            <div class="form">
                <div class="item">
                    <i class="fa fa-user-circle" aria-hidden="true">i>
                    <span style="color: white; font-size: large; ">账号:span>font><input type="text" name="name" id="name"
                                                                                           placeholder="请输入账号"
                                                                                           onblur="checkUserName()"/>
                    <div id="checkNameMsg">div>
                    <div id="checkMultiName">div>
                    <br>
                div>
    
                <div class="item">
                    <i class="fa fa-key" aria-hidden="true">i>
                    <span style="color: white; font-size: large; ">密码:span><input type="password" name="pwd" id="pwd"
                                                                                    placeholder="请输入密码"
                                                                                    onblur="checkPwd()"/>
                    <div id="checkPwdMsg">div>
                    <br>
                div>
    
                <div class="item">
                    <i class="fa fa-nick" aria-hidden="true">i>
                    <span style="color: white; font-size: large; ">昵称:span><input type="text" name="nickname"
                                                                                    id="nickname"
                                                                                    placeholder="请输入昵称"
                                                                                    onblur="checkNickName()"><br>
                    <div id="checkNickMsg">div>
                div>
    
                <div class="item">
                    <i class="fa fa-nick" aria-hidden="true">i>
                    <span style="color: white; font-size: large; ">头像:span><input type="file" id="upFile" value="选择文件"/>
                    <a href="javascript:void(0)" id="uploadFile" onclick="loadPic()">立即上传a>
                    <br>
                    <div id="divimg" style="width: 100px;height: 150px">
                        <img id="img" style="width: 140px;height: 180px;" alt="您还未上传图片"/>
                    div>
                    <br>
                    <div class="progress">
                        <div>
                        div>
                    div>
                    <div id="divNum">div>
                div>
    
                <button type="submit">注册button>
            div>
        div>
    form>
    
    <script type="text/javascript">
    
    
        function checkUserName() {
            var reg1 = /^[a-zA-Z]{5,10}$/;
            var userName = $("#name").val();
            if (!reg1.test(userName)) {
                $("#checkNameMsg").html("输入5-10个以字母开头的字串");
                return false;
            }
            $("#checkNameMsg").html("");
            $.ajax({
                url: "checkUserName.do",
                type: "post",
                /*  dataType: "json",*/
                data: userName,
                contentType: "text/html;charset=UTF-8",
                success: function (data) {
                    if (data =="error:Repeated") {
                        $("#checkMultiName").html("该账号已被注册");
    
                        return false;
                    } else {
                        $("#checkMultiName").html("该账号可用");
                        return true;
                    }
                }
            });
            // $("#checkNameMsg").html = ("OK");
        }
    
        function checkPwd() {
            var reg1 = /^(\w){6,10}$/;
            var userPwd = $("#pwd").val();
    
            if (!reg1.test(userPwd)) {
                $("#checkPwdMsg").html("只能输入6-10个字母、数字、下划线");
                return false;
            }
    
            $("#checkPwdMsg").html("OK");
        }
    
        function checkNickName() {
            if ($("#nickname").val().length == 0) {
                $("#checkNickMsg").html("请输入昵称");
                return false;
            }
            $("#checkNickMsg").html("OK");
        }
    
        function loadPic() {
    
            var photoFile = $("#upFile")[0].files[0];
    
            // 将文件传到这个对象中
            var formData = new FormData();
    
            formData.append("headerPicture", photoFile);
    
            $.ajax({
                    url: "/fileUpload2.do",
                    data: formData,//传送的数据
                    type: "post",
                    processData: false,//告诉浏览器发送的是一个对象   请求数据
                    contentType: false,//告诉浏览器 请求数据的类型 二进制类型
                    // dataType: "json",
                    success: function (data) {//接收返回来的数据并修改img标签里的内容
                        //console.log(data);
                       alert(data.msg);
                        $("#img").attr("src", data.newFileName);
                    },
                    xhr: function () {
                        var xhr = new XMLHttpRequest();
                        xhr.upload.addEventListener('progress', function (e) {
                            console.log(e);
                            var progressRate = (e.loaded / e.total) * 100 + '%';
                            if (photoFile != null) {
                                $("#divNum").text(progressRate);
                            }
                            if (photoFile != null) {
                                $('.progress > div').css('width', progressRate);
                            }
                        })
                        return xhr;
                    }
                }
            );
        }
    script>
    
    
    body>
    
    <footer>
        <div id="message-box">Hello, I'm CodeM!div>
    footer>
    
    html>

主页代码

    DOCTYPE html>
    <html lang="en">
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    head>
    <body>
    <span data-th-text="${user.name}">span>,welcome to here!!
    <button><a style="text-decoration-line: none"  href="showUser.do">查看所有用户a>button>
    body>
    html>

注册成功页

   DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>注册成功title>
        <script type="text/javascript"
                src="js/jquery-3.5.1.min.js">
        script>
    
    head>
    <body>
    <span data-th-text="${msg}">span>,两秒后返回登录页....,如果超时请  <a href="loginPage.html">手动返回a>
    body>
    html>

下载页

   DOCTYPE html>
    <html lang="en">
    <head>
        <title>Titletitle>
        <style>
            #playerTable {
                width: 50%;
                border: 3px solid cadetblue;
                margin: 0px auto;
                text-align: center;
            }
    
            #playerTable th, td {
                border: 1px solid gray;
            }
    
            #playerTable img {
                width: 100px;
                height: 100px;
            }
        style>
        <script type="text/javascript" src="js/jquery-3.5.1.min.js">script>
        <script>
            // 进入这个页面一上来就加载所有信息
            $(function () {
                $.ajax({
                    type: "post",
                    url: "getAllUser",/*获得所有信息*/
                    success: function (users) {
                        $.each(users, function (i, e) {
                            $("#playerTable").append('\n' +
                                '        ' + e.id + '\n' +
                                '        ' + e.name + '\n' +
                                '        ' + e.pwd + '\n' +
                                '        ' + e.nickname + '\n' +
                                '        \n' +
                                '            + e.picname + '" alt="" src>\n' +
                                '        \n' +
                                '        \n' +/*点击下载跳转链接,使得文件发送到用户端*/
                                '            +e.picname+'&filetype='+e.filetype+'">下载\n' +
                                '        \n' +
                                '    ')
                        })
                    }
                })
            })
        script>
    head>
    <body>
    <table id="playerTable" cellspacing="0xp" cellpadding="0px">
        <tr>
            <th>编号th>
            <th>账号th>
            <th>密码th>
            <th>昵称th>
            <th>头像th>
            <th>下载th>
        tr>
    
    table>
    body>
    html>

controller层

    package com.gavin.controller;
    import com.gavin.mapper.UserMapper;
    import com.gavin.pojo.User;
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.WebResource;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.tomcat.util.http.fileupload.IOUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.support.PropertiesLoaderUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.servlet.ModelAndView;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.util.*;
    /**
     * @author Gavin
     */
    @Controller
    public class FileController {
        //上传到的文件位置---非本地
    
        private String newFileName = null;
        private String fileType = null;
    
       private static ClassPathResource classPathResource = new ClassPathResource("/config/location.properties");
        Properties properties = PropertiesLoaderUtils.loadProperties(classPathResource);
    
        String pic_location = properties.getProperty("pic_location");
    
    
        @Qualifier(value = "sqlSessionFactory")
        private SqlSessionFactory sqlSessionFactory;
    
        public FileController() throws IOException {
        }
    
        @Autowired
        public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
            this.sqlSessionFactory = sqlSessionFactory;
        }
    
        /**
         * @return 返回查到的用户信息
         * @Desc 文件展示
         */
        @RequestMapping("/getAllUser")
        @ResponseBody
        public List<User> getAllUser() {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.getAllUser();
    //        返回一个json对象
            return users;
        }
    
    
        /**
         * 首页
         */
        @RequestMapping("/")
        public String Welcome(/*HttpServletRequest request*/) {
    
            return "loginPage.html";
        }
    
        /**
         * @param user 前端传来的用户信息
         * @return 处理结果
         * @Desc 登录检查
         */
    
        @PostMapping("/login.do")
        public String loginSys(@Param("user") User user, HttpServletRequest request) {
         //  System.out.println(user);
    //        如果没登陆过
            //如果user不为空,则查询user是否存在
            if (null != user) {
                SqlSession sqlSession = sqlSessionFactory.openSession();
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                Integer i = mapper.loginCheck(user);
                //如果存在则跳到main页面
                if (null != i) {
                    HttpSession session = request.getSession();
                    session.setAttribute("user", user);
                    return "../static/main.html";
                }
            }
            //如果不存在则重定向到
            // 登录页
            return "redirect:../static/loginPage.html";
    
        }
    
        /**
         * @param name 前端传来的用户名
         * @return 检验结果
         * @Desc 检查用户名唯一性
         */
        @RequestMapping("/checkUserName.do")
        @ResponseBody
        public String checkUser(@RequestBody String name) {
    
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Integer result = mapper.checkUser(name);
            sqlSession.close();
            if (null != result) {
                return "error:Repeated";
            }
            return "right:OK";
        }
    
    
        /**
         * @param user 前端传来的用户注册信息
         * @return 响应结果
         * @Desc 检查用户名唯一性
         */
        @PostMapping("/addUser.do")
        public Object addUser(@Param("user") User user) {
            ModelAndView model = new ModelAndView();
            System.out.println(user.toString());
            if (null != user) {
                user.setPicname(newFileName);
                user.setFiletype(fileType);
                System.out.println(user);
                SqlSession sqlSession = sqlSessionFactory.openSession();
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                int i = mapper.registerUser(user);
                sqlSession.close();
                if (i == 1) {
                    model.addObject("msg", "注册成功");
                    model.setViewName("../static/success.html");
    
                } else {
                    //        如果用户注册失败(网络原因,其他原因,那么注册的图片还要删除,这里不做处理)
                    model.addObject("msg", "注册失败");
                    model.setViewName("../static/registPage.html");
                }
            }
            return model;
        }
    
    
        @RequestMapping("/fileUpload2.do")
        @ResponseBody
        public Map<String, String> upDataPicture(MultipartFile headerPicture, HttpServletRequest request) throws IOException {
            Map<String, String> map = new HashMap<>(1);
    //        如果文件不存在
            if (headerPicture == null) {
                map.put("msg", "请上传图片!");
                return map;
            }
    //有文件,则获取文件名
            String originalFilename = headerPicture.getOriginalFilename();
    //        控制文件的大小
            Integer size = 1024 * 1024 * 10;
            if (headerPicture.getSize() > size) {
                map.put("msg", "文件大小不超过10M");
                return map;
            }
    //        避免名字冲突,用UUID替换文件名,但是扩展名不变
            String uuid = UUID.randomUUID().toString();
    //        获取拓展名,只支持jpg与png
            String[] exName = {".jpg", ".png"};
            String extendsName = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!(exName[0].equals(extendsName) || exName[1].equals(extendsName))) {
                map.put("msg", "文件类型不符合要求");
                return map;
            }
    //拼接成新名字
            newFileName = uuid.concat(extendsName);
            System.out.println(newFileName);
    
    
    //创建 jersey 包中的client对象,用于跨服务器请求
            Client client = Client.create();
            System.out.println(client);
            WebResource resource = client.resource(pic_location + newFileName);
            String result = resource.put(String.class, headerPicture.getBytes());
            System.out.println(result);
            map.put("msg", "文件上传成功");
    //        返回新生成的文件名
            map.put("newFileName", pic_location + newFileName);
            fileType = headerPicture.getContentType();
            map.put("fileType", fileType);
            return map;
        }
        @RequestMapping("/showUser.do")
        public String showUser() {
    
            return "../static/picDown.html";
        }
    
        /**
         * 文件下载
         *
         * @param picname  文件名
         * @param fileType 文件类型--前端
         * @param resp     响应对象
         * @throws IOException
         */
    
        @RequestMapping("/fileDownload.do")
        public void fileDownLoad(String picname, String fileType, HttpServletResponse resp) throws IOException {
            //设置响应头
    //        这里如果传过来id则还要到数据库查,不如直接穿过来文件名
    //    解析文件名----数据库里没有直接存文件格式,所以要在这里解析文件格式,但是这列格式并非前端识别的格式,所以还是修改之前的在用户表上添加前端文件格式
    
    //    保存数据到磁盘上,不在浏览器上直接解析
            resp.setHeader("Content-Disposition", "attachment;filename=" + picname);
            resp.setContentType(fileType);
    //        获取一个文件输入流
            InputStream inputStream = new URL(pic_location + picname).openStream();
    //        浏览器获得输出文件
            ServletOutputStream outputStream = resp.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
        }
    
    }

简单的测试一下
springboot实现文件的上传下载_第2张图片springboot实现文件的上传下载_第3张图片

登陆成功界面
springboot实现文件的上传下载_第4张图片
注册成功界面
springboot实现文件的上传下载_第5张图片

下载页面springboot实现文件的上传下载_第6张图片

你可能感兴趣的:(java,#,前端,spring,spring,boot,java,spring)