Spring MVC实现文件上传
【摘要】 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项目
整合SSM框架
配置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;
}
}
结语
项目演示就到此结束了,感兴趣的读者可在下方获取源码,文件上传是非常常用的技术,一定要搞懂,不明白的可以多敲 上几遍,熟能生巧,相信你持续的努力,终有一日你就会实现你的梦想,编程路上,我们都是追梦人~
如果你觉得本文写的不错的话,那就给博主点个赞吧~~
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)