一、第一步,
第一步依然是创建数据库,我简单设计了三个字段(file_id,file_name,create_time)
CREATE TABLE `txtfile` (
`file_id` int NOT NULL AUTO_INCREMENT,
`file_name` varchar(45) NOT NULL,
`create_time` varchar(45) NOT NULL,
PRIMARY KEY (`file_id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb3
然后springboot配置文件
application.yml
mybatis:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:mapper/*.xml
type-aliases-package: edu.wsm.doamin
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1/somefile?useUnicode=true&characterEncoding=utf8
username: root
password: root
thymeleaf:
cache: false
encoding: utf-8
prefix: classpath:templates/
suffix: .html
check-template: true
servlet:
content-type: text/html
check-template-location: true
server:
port: 80
maven包管理
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>edu.wsm</groupId>
<artifactId>fileup-download</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>fileup-download</name>
<description>fileup-download</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、第二部,
接着实现代码,依然采用经典的MVC结构,代码实现如下:
1.实体类domain
SomeFile.java
package edu.wsm.domain;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @ClassName SomeFile
* @Description TODO
* @Author Deer·Wang
* @Date 2021/12/11 13:11
* @Version 1.0
**/
@Data
@NoArgsConstructor
public class SomeFile {
private Integer fileId;
private String fileName;
private String createTime;
}
2.dao层
FileOperation.java
package edu.wsm.dao;
import edu.wsm.domain.SomeFile;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @ClassName FileOperation
* @Description TODO
* @Author Deer·Wang
* @Date 2021/12/11 13:13
* @Version 1.0
**/
@Mapper
public interface FileOperation {
public List<SomeFile> select();
public void insert(SomeFile someFile);
}
3.service层
FileService.java
package edu.wsm.service;
import edu.wsm.dao.FileOperation;
import edu.wsm.domain.SomeFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.util.List;
/**
* @ClassName FileService
* @Description TODO
* @Author Deer·Wang
* @Date 2021/12/11 13:16
* @Version 1.0
**/
@Service
public class FileService {
@Resource
private FileOperation fileOperation;
/**
* 查询所有文件
* @return
*/
public List<SomeFile> searchAll(){
List<SomeFile> fileList = fileOperation.select();
return fileList;
}
/**
* 添加文件
* @param someFile SomeFile类对象
* @param multipartFile 前端上传的文件
*/
public void add(SomeFile someFile, MultipartFile multipartFile){
if(multipartFile!=null){
try {
multipartFile.transferTo(new File("这里写你文件存储的路径"+multipartFile.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
fileOperation.insert(someFile);
}
}
}
4.Mapper文件
FileOperationMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="edu.wsm.dao.FileOperation">
<resultMap id="fileOperationMap" type="edu.wsm.domain.SomeFile">
<id column="file_id" property="fileId" javaType="java.lang.Integer"></id>
<result column="file_name" property="fileName" javaType="java.lang.String"></result>
</resultMap>
<select id="select" resultMap="fileOperationMap">
select * from txtfile
</select>
<insert id="insert">
insert into txtfile (file_name,create_time) values (#{fileName},#{createTime})
</insert>
</mapper>
5.controller层
FileController.java
package edu.wsm.controller;
import edu.wsm.domain.SomeFile;
import edu.wsm.service.FileService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.util.List;
/**
* @ClassName FileController
* @Description TODO
* @Author Deer·Wang
* @Date 2021/12/11 13:17
* @Version 1.0
**/
@Controller
@RequestMapping("/file")
public class FileController {
@Resource
private FileService fileService;
/**
* 查询文件并把文件集合传给showFile.html
* @param model
* @return
*/
@RequestMapping("/search")
public String search(Model model){
List<SomeFile> fileList = fileService.searchAll();
model.addAttribute("fileList",fileList);
return "showFile";
}
/**
* 接收游览器上传的文件并做处理
* @param file
* @param model
* @return
* @throws IOException
*/
@PostMapping("/add")
public String add(MultipartFile file,Model model) throws IOException {
//判断上传的文件是否为空
if(!file.isEmpty()){
SomeFile someFile = new SomeFile();
LocalDateTime localDateTime = LocalDateTime.now();
someFile.setFileName(file.getOriginalFilename());
someFile.setCreateTime(localDateTime.toLocalDate()+" "+localDateTime.toLocalTime());
fileService.add(someFile,file);
}else {
model.addAttribute("error","文件不存在或文件过大或格式不对");
}
return "redirect:/file/search";
}
/**
* 下载文件
* @param response 响应
* @param fileName 要下载的文件名
* @throws IOException
*/
@PostMapping("/download")
public void download(HttpServletResponse response, String fileName) throws IOException {
//从服务器本地读取文件
File file = new File("这里填你文件存储的路径"+fileName);
//判断文件是否存在
if(!file.exists()){
response.sendError(404,"你下载的资源不存在!!!");
}
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
//响应输出流
OutputStream outputStream = response.getOutputStream();
//设置响应头
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
//将文件以流的方式传给前端
int i = 0;
byte[] buff = new byte[1024];
while ((i = bis.read(buff)) != -1) {
outputStream.write(buff, 0, i);
}
bis.close();
outputStream.close();
}
}
6.View界面
showFile.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>信息列表</title>
</head>
<body>
<h1>!!!非常炫酷的View界面!!!</h1>
<h4>!!! 上传文件不要超过10k !!!</h4>
<h4>!!!上传txt格式的文本!!!</h4>
<table border="1px" cellspacing="0" cellpadding="1">
<tr>
<th>文件目录</th><th>时间</th><th>操作</th>
</tr>
<tr th:each="files:${fileList}">
<td th:text="${files.fileName}"></td>
<td th:text="${files.createTime}"></td>
<td>
<!-- <a th:href="@{/file/download}" th:method="post" th:download="${files.fileName}">下载</a>-->
<form th:action="@{/file/download}" method="post" enctype="multipart/form-data">
<input type="hidden" name="fileName" th:value="${files.fileName}"/>
<input type="submit" value="下载"/>
</form>
</td>
</tr>
</table>
<p>----------------------------</p>
<div style="height: 70px;width: 500px;background-color: #efff43">
<form method="post" enctype="multipart/form-data" th:action="@{/file/add}">
<input type="file" name="file" value=""/>| <input type="submit" value="上传">
</form>
</div>
</body>
</html>
error.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>!!!资源有误!!!</h1>
<p>原因: 1.可能你上传的资源过大或不存在 2.下载的资源不存在</p>
<a th:href="@{/file/search}">点此返回</a>
</body>
</html>