• Spring Boot实现文件上传功能


    ✨Spring Boot实现文件上传功能


    📃个人主页: 不断前进的皮卡丘
    🌞博客描述: 梦想也许遥不可及,但重要的是追梦的过程,用博客记录自己的成长,记录自己一步一步向上攀登的印记
    🔥网站推荐:千里之行,始于足下。每天坚持刷题,巩固所学知识,也为将来找工作,面试做好准备----- 刷题神器
    各大互联网大厂面试真题。基础题库到进阶题库等各类面试题应有尽有!
    牛客网面经合集,满足大厂面试技术深度,快速构建Java核心知识体系大厂面试官亲授,备战面试与技能提升,主要考点+主流场景+内功提升+真题解析

    前端处理

    • 通过form表单来上传文件
    • 提交方式为post
    • enctype格式为"multipart/form-data"
    • input类型为file
    • name属性必须和Controller中方法的形参名称一致
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    head>
    <body>
        <h2>用户注册h2>
        <form action="/register" method="post" enctype="multipart/form-data">
            用户名:<input type="text" name="username"><br><br>
            密码  :<input type="password" name="password"><br><br>
            头像  :<input type="file" name="uploadFile"><br><br>
            <input type="submit" value="提交">
        form>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    后端处理

    创建一个数据库用来保存登录的用户名,密码,文件名
    在这里插入图片描述

    我们可以写一个工具类

    public class UUIDUtils {
        public static String createNewUUID(){
            String uuid = UUID.randomUUID().toString();
            //如果要把uuid的-去掉替换成空字符串 然后需要把32为字符串变成64字符串
            uuid = uuid.replace("-", "");
            return uuid+uuid;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    实体类User

    @Data
    public class User {
        private Integer id;
        private String username;
        private String password;
        private String filename;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Controller

    @Controller
    public class UserController {
        @Autowired
        private UserService userService;
    
        /**
         * 显示注册画面
         * @return
         */
        @RequestMapping("/show")
        public String show(){
            return "/page/register.html";
        }
        @PostMapping("/register")
        public String register(User user, @RequestParam("uploadFile") MultipartFile uploadFile){
            System.out.println("用户:"+user);
            System.out.println("文件:"+uploadFile);
            //创建本地文件
            //思考文件名,文件名要是唯一的 必须要保证每一个用户注册上传的图片,文件等,必须保存成唯一的文件名
            //Java技术 Java UUID User Unique ID 本身用于给用户指定唯一的ID,可以用它来产生唯一的随机字符串
            //uuid默认返回的是32位字母组成的随机字符串,重复的概率几乎为0
            //创建唯一文件名
            String fileName= UUIDUtils.createNewUUID();
            //我们需要文件的后缀也应该不是写死的,前端上传的后缀是啥,我们保存的就是什么
            //获取原生文件的文件名
            String originalFilename = uploadFile.getOriginalFilename();
            System.out.println(originalFilename);
            //创建文件的后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //创建新的文件路径
            String filePath=fileName+suffix;
    
            File srcFile = new File("D:/springboot/download/img/"+filePath);
            try {
                //把前端传送的文件保存在本地中
                uploadFile.transferTo(srcFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            user.setFilename(filePath);
            try {
                userService.register(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }
    
    
    }
    
    
    • 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

    Service

    public interface UserService {
        void register(User user) throws Exception;
    }
    
    
    • 1
    • 2
    • 3
    • 4

    Service实现类

    @Service
    public class UserServiceImpl implements UserService {
        @Autowired
        private UserMapper userMapper;
        @Override
        public void register(User user) throws Exception {
            userMapper.insert(user);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Mapper

    @Mapper
    public interface UserMapper {
        @Insert("insert into user values(default,#{username},#{password},#{filename})")
        void insert(User user);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    物理路径和虚拟路径映射

    先准备好页面jsp

    <%@page language="java" isELIgnored="false" pageEncoding="UTF-8" contentType="text/html; UTF-8" %>
      <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
        DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="UTF-8">
            <title>Titletitle>
          head>
          <body>
            <h2>文件的上传h2>
            <form action="/file/upload" method="post" enctype="multipart/form-data">
              文件上传:<input type="file" name="uploadFile"><br><br>
              <input type="submit" value="提交">
            form>
          body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    <%@page language="java" isELIgnored="false" pageEncoding="UTF-8" contentType="text/html; UTF-8" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    head>
    <body>
        <img src="/img/${filePath}">图像img>
        路径:${filePath}
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    编写Controller

    @Controller
    @RequestMapping("/file")
    public class FileUploadController {
        /**
        * 显示画面
        * @return
        */
        @RequestMapping("/show")
        public String show(){
            return "file.jsp";
        }
        
        @RequestMapping(value = "/upload",method = RequestMethod.POST)
        public String fileUpload(MultipartFile uploadFile, HttpSession session){
            //利用uuid创建唯一的字符串 让这个字符串作为文件名
            String fileName = UUIDUtils.createNewUUID();
            
            //获取上传文件的文件名
            String originalFilename = uploadFile.getOriginalFilename();
            //获取后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //创建文件保存路径
            String filePath=fileName+suffix;
            File srcFile=new File("D:/springboot/download/img/"+filePath);
            //把前端文件保存在本地
            try {
                uploadFile.transferTo(srcFile);
                //把文件存放在本地的文件路径保存在session域中
                session.setAttribute("filePath", filePath);
                
            } catch (IOException e) {
                e.printStackTrace();
            }
            //我们希望网页上可以把图片显示出来
            System.out.println("文件存放路径:"+filePath);
            return "show.jsp";
        }
        
    }
    
    
    • 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

    在这里插入图片描述

    不过,我们可以发现,当我们点击提交的时候,图片还是无法显示

    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        //实现资源的虚拟路径和物理路径的映射
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
             registry.addResourceHandler("/img/**")
                     .addResourceLocations("file:"+"D:\\springboot\\download\\img\\");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    addResourceHandler(“xxx”) 用于指定对外暴露的访问路径,addResourceLocations(“xxx”) 用于指定文件放置路径

    在这里插入图片描述

  • 相关阅读:
    esbuild中文文档-输出内容配置项(Output contents - Banner、Charset、Footer)
    Java Number类
    从0开始python学习-26.selenium 强制等待、显示等待、隐式等待
    简易计算器的实现:使用C语言进行基础算术运算
    Android 通过Room操作SQLite数据库
    基于Java毕业设计定西扶贫惠农推介系统源码+系统+mysql+lw文档+部署软件
    MySQL-MHA
    第1章 物联网模式简介---物联网参考架构
    NSS [HNCTF 2022 WEEK2]ohmywordpress(CVE-2022-0760)
    【allegro 17.4软件操作保姆级教程五】布线前准备之过孔、差分对、布线集合添加
  • 原文地址:https://blog.csdn.net/qq_52797170/article/details/126281073