Spring MVC实现文件上传

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: Spring MVC实现文件上传

Spring MVC实现文件上传

本周为大家带来Web开发中最常用的技术,文件上传,Spring MVC实现文件上传并查看图片文件

数据表

employee

CREATE TABLE `employee` (
  `e_id` int(11) NOT NULL AUTO_INCREMENT,
  `e_name` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '员工姓名',
  `e_sex` int(11) DEFAULT NULL COMMENT '员工性别:0:男 1:女',
  `e_head_pic` varchar(256) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '员工头像',
  `e_join_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入职日期',
  PRIMARY KEY (`e_id`)
) 

效果图

在这里插入图片描述

项目结构

在这里插入图片描述

Java源码结构

在这里插入图片描述

配置文件结构

在这里插入图片描述

前端结构

在这里插入图片描述

环境搭建

使用Maven创建Web项目

IDEA创建JavaWeb项目并配置Tomcat

整合SSM框架

整合SSM

配置Tomcat虚拟访问路径

配置Tomcat虚拟访问路径

pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SSMFileUpload</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>

        <!-- mybatis依赖的坐标 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>

        <!-- java连接mysql的驱动坐标 -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

Spring MVC文件上传配置

打开==springmvc.xml==配置文件,添加如下内容

<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置文件上传大小,单位是字节 -->
    <property name="maxUploadSize" value="5000000"></property>
    <property name="defaultEncoding" value="UTF-8" />
    <property name="resolveLazily" value="true" />
</bean>

核心源码

EmployeeController

package com.wanshi.controller;

import com.wanshi.bean.Employee;
import com.wanshi.service.EmployeeService;
import com.wanshi.util.FileUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/add")
    public String add() {
        return "add";
    }

    @SneakyThrows
    @RequestMapping("/addHandle")
    public String add(MultipartFile head_pic, HttpServletRequest request)  {
        try {
            String eName = request.getParameter("e_name");
            String eSex = request.getParameter("e_sex");
            String joinDate = request.getParameter("e_join_date");
            String headPic = FileUtil.upload(head_pic, "");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Employee employee = new Employee();
            employee.setE_name(eName);
            employee.setE_sex(Integer.valueOf(eSex));
            employee.setE_join_date(sdf.parse(joinDate));
            employee.setE_head_pic(headPic);

            employeeService.insert(employee);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/emp/list";
    }

    @RequestMapping("/list")
    public String list(Model model){
        List<Employee> empList = employeeService.list();
        model.addAttribute("empList", empList);
        return "list";
    }
}

FileUtil

package com.wanshi.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class FileUtil {

    public static String upload(MultipartFile head_pic, String oldHeadPic) throws IOException {
        String finalFileName = "";
        if (head_pic.getSize() > 0) {
            InputStream inputStream = head_pic.getInputStream();
            String originalFilename = head_pic.getOriginalFilename();
            new File("C:/uploads/img/"+oldHeadPic).delete();
            //生成目标文件
            String destName = UUID.randomUUID().toString().replace("-", "");
            //获取源文件的后缀名
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            finalFileName = destName+extName;
            //目标文件
            File file = new File("C:/uploads/img/"+finalFileName);
            if (!file.exists()) {
                file.mkdirs();
            }
            //开始上传
            head_pic.transferTo(file);
        }
        return finalFileName;
    }

}

结语

项目演示就到此结束了,感兴趣的读者可在下方获取源码,文件上传是非常常用的技术,一定要搞懂,不明白的可以多敲 上几遍,熟能生巧,相信你持续的努力,终有一日你就会实现你的梦想,编程路上,我们都是追梦人~

如果你觉得本文写的不错的话,那就给博主点个赞吧~~

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
28天前
|
缓存 前端开发 Java
Spring MVC 面试题及答案整理,最新面试题
Spring MVC 面试题及答案整理,最新面试题
85 0
|
28天前
ssm(Spring+Spring mvc+mybatis)——updateDept.jsp
ssm(Spring+Spring mvc+mybatis)——updateDept.jsp
10 0
|
28天前
ssm(Spring+Spring mvc+mybatis)——showDept.jsp
ssm(Spring+Spring mvc+mybatis)——showDept.jsp
9 0
|
27天前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
22 0
|
27天前
|
SQL Java 数据库连接
挺详细的spring+springmvc+mybatis配置整合|含源代码
挺详细的spring+springmvc+mybatis配置整合|含源代码
34 1
|
5天前
|
数据采集 前端开发 Java
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
19 3
|
5天前
|
存储 前端开发 Java
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
12 1
|
5天前
|
前端开发 Java Spring
数据之桥:深入Spring MVC中传递数据给视图的实用指南
数据之桥:深入Spring MVC中传递数据给视图的实用指南
20 3
|
15天前
|
前端开发 安全 Java
使用Java Web框架:Spring MVC的全面指南
【4月更文挑战第3天】Spring MVC是Spring框架的一部分,用于构建高效、模块化的Web应用。它基于MVC模式,支持多种视图技术。核心概念包括DispatcherServlet(前端控制器)、HandlerMapping(请求映射)、Controller(处理请求)、ViewResolver(视图解析)和ModelAndView(模型和视图容器)。开发流程涉及配置DispatcherServlet、定义Controller、创建View、处理数据、绑定模型和异常处理。
使用Java Web框架:Spring MVC的全面指南
|
21天前
|
敏捷开发 监控 前端开发
Spring+SpringMVC+Mybatis的分布式敏捷开发系统架构
Spring+SpringMVC+Mybatis的分布式敏捷开发系统架构
50 0