springboot文件上傳下載實戰 —— 登錄功能、展示所有文件

GitHub:https://github.com/szluyu99/springboot_files

後續內容: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>

數據庫建表與環境準備

需求分析:

建表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 網址,輸入用戶名與密碼,點擊登錄,此時會跳轉到展示所有文件頁面。
在這裏插入圖片描述
但是由於目前數據庫中沒有數據,所以什麼都不顯示。
在這裏插入圖片描述
接下來就要開始做文件上傳功能了。

可以看這個:springboot文件上傳下載實戰 ——文件上傳、下載、在線打開、刪除

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章