springboot文件上传下载实战
创建项目
通过 Spring Initializr 或者 直接创建一个 Maven 项目来构建一个 springboot 项目,我们通过 Spring Initializr 来创建:
输入项目信息:
选择 Sprig Wbe 依赖,其他依赖可以看我后面的 pom.xml。
删除一些用不到的文件和文件夹(比如 test 下的文件),基础的 spring boot 项目结构如下:
pom.xml
这些是本项目中要用到依赖,直接复制我的 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--继承springboot父项目-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
</parent>
<groupId>com.yusael</groupId>
<artifactId>myfiles</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>myfiles</name>
<description>文件的上传与下载实战</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--引入springboot的web支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.43</version>
<scope>runtime</scope>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--commons-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
数据库建表与环境准备
需求分析:
- 要做的是文件管理系统,自然要存储文件的信息,需要文件信息表(t_files)
- 我们要做用户的登录功能,需要用户表(t_user)(此处为了简略,省略注册,若想看注册,可以看 基于springboot+thymeleaf+mybatis的员工管理系统 —— 登录与注册)
建表SQL
用户表 t_user 的 SQL:
CREATE TABLE `t_user` (
`id` int(8) NOT NULL,
`username` varchar(80) DEFAULT NULL,
`password` varchar(80) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
文件信息表 t_files 的 SQL:
CREATE TABLE `t_files` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`oldFileName` varchar(200) DEFAULT NULL,
`newFileName` varchar(300) DEFAULT NULL,
`ext` varchar(20) DEFAULT NULL,
`path` varchar(300) DEFAULT NULL,
`size` varchar(200) DEFAULT NULL,
`type` varchar(120) DEFAULT NULL,
`isImg` varchar(8) DEFAULT NULL,
`downcounts` int(6) DEFAULT NULL,
`uploadTime` datetime DEFAULT NULL,
`userId` int(8) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userId` (`userId`),
CONSTRAINT `userId` FOREIGN KEY (`userId`) REFERENCES `t_user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8;
数据库建完表以后,还需要在 application.properties 中配置。
配置文件 application.properties
spring.application.name=files
server.port=8989
server.servlet.context-path=/files
##配置thymleaf(下面注释的是默认配置, 可以不设置)
#spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.servlet.content-type=text/html
#本项目使用了热部署, 想让热部署生效必须配置这个
spring.thymeleaf.cache=false
#默认无法直接访问templates下的页面, 需要设置
spring.resources.static-locations=classpath:/templates/, classpath:/static/
##mysql配置
#指定连接池类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#指定驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#指定url
spring.datasource.url=jdbc:mysql://localhost:3306/userfiles?characterEncoding=UTF-8
#指定用户名
spring.datasource.username=root
#指定密码
spring.datasource.password=1234
#指定mapper配置文件位置
mybatis.mapper-locations=classpath:/com/yusael/mapper/*.xml
#指定起别名了的类
mybatis.type-aliases-package=com.yusael.entity
#允许最大上传大小
spring.servlet.multipart.max-file-size=500MB
spring.servlet.multipart.max-request-size=500MB
##日志配置
logging.level.root=info
logging.level.com.yusael.dao=debug
整体架构
搭建出项目的整体架构如下,然后可以开始进行开发各个功能了。
在启动类中加上 @MapperScan("com.yusael.dao")
来扫描 com.yusae.dao
包。
@SpringBootApplication
@MapperScan("com.yusael.dao")
public class MyfilesApplication {
public static void main(String[] args) {
SpringApplication.run(MyfilesApplication.class, args);
}
}
前端页面
这次的实战主要是为了熟悉文件上传与下载,因此页面十分简易。
登录页面 login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h1>欢迎访问用户文件管理系统</h1>
<form th:action="@{/user/login}" method="post">
username: <input type="text" name="username"/> <br>
password: <input type="password" name="password"/> <br>
<input type="submit" value="登录">
</form>
</body>
</html>
文件列表页面 showAll.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户文件列表页面</title>
</head>
<body>
<h1>欢迎: <span th:if="${session.user != null}" th:text="%{session.user.username}"/></h1>
<h2>文件列表</h2>
<table border="1px">
<tr>
<th>ID</th>
<th>文件原始名称</th>
<th>文件的新名称</th>
<th>文件后缀</th>
<th>存储路径</th>
<th>文件大小</th>
<th>类型</th>
<th>是否图片</th>
<th>下载次数</th>
<th>上传时间</th>
<th>操作</th>
</tr>
<tr th:each="file : ${files}">
<td><span th:text="${file.id}"/></td>
<td><span th:text="${file.id}"/></td>
<td><span th:text="${file.oldFileName}"/></td>
<td><span th:text="${file.newFileName}"/></td>
<td><span th:text="${file.ext}"/></td>
<td><span th:text="${file.path}"/></td>
<td><span th:text="${file.size}"/></td>
<td><span th:text="${file.type}"/></td>
<td>
<span th:text="${file.isImg}"/>
<img th:if="${file.isImg}=='是'" style="height: 40px;height: 100px" th:src="${#servletContext.contextPath} + ${file.path} + '/' + ${file.newFileName}" alt="">
</td>
<td th:id="${file.id}"><span th:text="${file.downcounts}"/></td>
<td><span th:text="${#dates.format(file.uploadTime, 'yyyy-MM-dd hh:mm:ss')}"/></td>
<td>
<a th:href="@{/file/download(id=${file.id})}">下载</a>
<a th:href="@{/file/download(id=${file.id},openStyle='inline')}">在线打开</a>
<a th:href="@{/file/delete(id=${file.id})}">删除</a>
</td>
</tr>
</table>
<hr>
<h3>上传列表</h3>
<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="aaa">
<input type="submit" value="上传文件">
</form>
</body>
</html>
页面跳转控制器
com.yusael.controller
包下创建 IndexController.java
:
package com.yusael.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/index")
public String index() {
return "login";
}
}
登录功能
com.yusael.entity
包下创建数据库映射的实体类 User.java
:
package com.yusael.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
private Integer id;
private String username;
private String password;
}
com.yusael.dao
包下创建 UserDAO.java
:
package com.yusael.dao;
import com.yusael.entity.User;
import org.apache.ibatis.annotations.Param;
public interface UserDAO {
User login(@Param("username") String username, @Param("password") String password);
}
resources/com/yusael/mapper
目录下创建接口 UserDAOMapper.xml
:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yusael.dao.UserDAO">
<!--登录-->
<select id="login" resultType="User">
select id, username, password from t_user
where username = #{username} and password = #{password}
</select>
</mapper>
com.yusael.service
包下创建接口 UserService.java
:
package com.yusael.service;
import com.yusael.entity.User;
public interface UserService {
User login(String username, String password);
}
com.yusael.service
包下创建接口的实现类 UserServiceImpl.java
:
package com.yusael.service;
import com.yusael.dao.UserDAO;
import com.yusael.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public User login(String username, String password) {
return userDAO.login(username, password);
}
}
com.yusael.dao
包下创建 UserController.java
:
package com.yusael.controller;
import com.yusael.entity.User;
import com.yusael.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(String username, String password, HttpSession session) {
User login = userService.login(username, password);
if (login != null) {
session.setAttribute("user", login); // 用户存在
System.out.println("登录成功!");
return "redirect:/file/showAll";
} else {
return "redirect:/index"; // 没有该用户, 跳转回登录界面
}
}
}
登录功能测试
在数据库的 t_user 表中存储一条数据:
浏览器输入网址:http://localhost:8989/files/index
,来到登陆界面,利用数据库中的数据进行登录。
由于我们还没有开发好下面的页面,显示这个是正常的。
我们也可以在 UserController.java
中增加一个输出语句来确保正确登录。
展示所有文件
com.yusael.entity
包下创建数据库映射的实体类 UserFilejava
:
package com.yusael.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
public class UserFile {
private Integer id;
private String oldFileName;
private String newFileName;
private String ext;
private String path;
private String size;
private String type;
private String isImg;
private Integer downcounts;
private Date uploadTime;
private Integer userId; // 用户外键
}
com.yusael.dao
包下创建 UserFileDAO
:
package com.yusael.dao;
import com.yusael.entity.UserFile;
import java.util.List;
public interface UserFileDAO {
// 根据登录用户id获取用户的文件目录
List<UserFile> findByUserId(Integer id);
}
com/yusael/mapper
目录下创建 UserFileDAOMapper.xml
:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yusael.dao.UserFileDAO">
<!--根据用户id查询文件信息-->
<select id="findByUserId" parameterType="Integer" resultType="UserFile">
select id,oldFileName,newFileName,ext,path,size,type,isImg,downcounts,uploadTime,userId
from t_files
where userId = #{id}
</select>
</mapper>
com.yusael.service
包下创建 UserFileService.java
:
package com.yusael.service;
import com.yusael.entity.User;
public interface UserService {
User login(String username, String password);
}
com.yusael.service
包下创建 UserFileServiceImpl.java
:
package com.yusael.service;
import com.yusael.dao.UserFileDAO;
import com.yusael.entity.User;
import com.yusael.entity.UserFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserFileServiceImpl implements UserFileService{
@Autowired
private UserFileDAO userFileDAO;
@Override
public List<UserFile> findById(Integer id) {
return userFileDAO.findByUserId(id);
}
}
com.yusael.controller
包下创建 UserFileController.java
:
package com.yusael.controller;
import com.yusael.entity.User;
import com.yusael.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(String username, String password, HttpSession session) {
User login = userService.login(username, password);
if (login != null) {
session.setAttribute("user", login); // 用户存在, 跳转到展示所有文件页面
System.out.println("登录成功!");
System.out.println(login);
return "redirect:/file/showAll";
} else {
return "redirect:/index"; // 没有该用户, 跳转回登录界面
}
}
}
展示所有文件功能测试
http://localhost:8989/files/index
网址,输入用户名与密码,点击登录,此时会跳转到展示所有文件页面。
但是由于目前数据库中没有数据,所以什么都不显示。
接下来就要开始做文件上传功能了。