栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot实现文件的上传下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot实现文件的上传下载

SpringBoot文件上传与下载

文件的上传与下载

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

 
    
      commons-fileupload
      commons-fileupload
      1.4
    
    
      commons-io
      commons-io
      2.8.0
    

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

    package com.gavin.fileupload;
       import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    
    @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,准备一个服务器,用于存放上传的文件;

修改端口号和修改只读为false;

启动文件服务器

跨服务器上传/下载的依赖

先搭建一个框架—>>

登录页–>

    
    
    
        
        登录页面
      
    
    
    

欢迎访问学生管理系统

账号:
密码:


注册页代码

    
    
    
    
        注册页
        
        
        
        
    
    
    
    
账号:

密码:

昵称:
头像: 立即上传
您还未上传图片

Hello, I'm CodeM!

主页代码

    
    
    
    
        
        Title
    
    
    ,welcome to here!!
    
    
    

注册成功页

   
    
    
        
        注册成功
        
    
    
    
    ,两秒后返回登录页....,如果超时请  手动返回
    
    

下载页

   
    
    
        Title
        
        
        
    
    
    
编号 账号 密码 昵称 头像 下载

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.*;
    
    @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;
        }
    
        
        @RequestMapping("/getAllUser")
        @ResponseBody
        public List getAllUser() {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List users = mapper.getAllUser();
    //        返回一个json对象
            return users;
        }
    
    
        
        @RequestMapping("/")
        public String Welcome() {
    
            return "loginPage.html";
        }
    
        
    
        @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";
    
        }
    
        
        @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";
        }
    
    
        
        @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 upDataPicture(MultipartFile headerPicture, HttpServletRequest request) throws IOException {
            Map 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";
        }
    
        
    
        @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);
        }
    
    }

简单的测试一下

登陆成功界面

注册成功界面

下载页面

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/731660.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号