1、配置
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.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>uploaddemo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>uploaddemo1</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
#端口号
server.port=8081
#Thymeleaf配置
#Thymeleaf的编码
spring.thymeleaf.encoding=UTF-8
#热部署静态文件,页面修改后会立即生效
spring.thymeleaf.cache=false
#使用HTML5的标准
spring.thymeleaf.mode=HTML5
#热部署配置
#开启devtools
spring.devtools.restart.enabled=true
#监听目录
spring.devtools.restart.additional-paths=src/main/java
#数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/uploaddb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#上传配置
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
spring.servlet.multipart.resolve-lazily=false
2、上传页面
upload.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>文件</title>
</head>
<body>
<br>
<hr>
<h3>上传文件</h3>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
效果
controller方法
@PostMapping("/upload")
public String upload(HttpSession session, @RequestParam("file") MultipartFile file, RedirectAttributes attributes)
throws IOException {
System.out.println("准备上传");
if (file.isEmpty()) {
attributes.addFlashAttribute("msg", "上传的文件不能为空");
return "";
}
// 获取原始文件名称
String originalFilename = file.getOriginalFilename();
System.out.println("原始文件名称==" + originalFilename);
// 获取文件后缀名
// String extension = "." + FilenameUtils.getExtension(originalFilename); //.jpg
// 获取新文件名称 命名:时间戳+UUID+后缀
String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString()
+ originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
// 获取资源路径 classpath的项目路径+/static/files classpath就是resources的资源路径
String path = ResourceUtils.getURL("classpath:").getPath() + "static/files/";
System.out.println("资源路径==" + path);
// 新建一个时间文件夹标识,用来分类
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// 全路径(存放资源的路径) 资源路径+时间文件夹标识
String dataDir = path + format;
System.out.println("全路径==" + dataDir);
// 全路径存放在文件类中,判断文件夹是否存在不存在就创建
File dataFile = new File(dataDir); // 也可以直接放进去进行拼接 File dataFile = new File(path,format);
if (!dataFile.exists()) {
dataFile.mkdirs();
}
// 文件上传至指定路径
file.transferTo(new File(dataFile, newFileName));
int b = upload1Mapper.insertUpload(originalFilename, dataDir, newFileName);
System.out.println(b);
if (b == 1) {
attributes.addFlashAttribute("msg", "保存成功!");
} else {
attributes.addFlashAttribute("msg", "保存失败!");
}
System.out.println("上传结束");
return "redirect:/downloads";
}
3、展示与下载页download.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>用户文件列表</title>
</head>
<body>
<!--快捷生成 table>tr>th*11 + table键-->
<table border="1px">
<tr>
<th>ID</th>
<th>文件原始名称</th>
<th>文件路径</th>
<th>操作</th>
</tr>
<tr th:each="files : ${fileUploadsList}">
<th th:text="${files.id}">1</th>
<th th:text="${files.name}">aa.txt</th>
<th th:text="${files.savepath}">/file</th>
<th>
<a th:href="@{/downloadd(id=${files.id},openStyle='attachment')}">下载</a>
</th>
</tr>
</table>
</body>
</html>
controller方法
@GetMapping("/downloads")
public String fileAll(HttpSession session, Model model) {
List<Upload1> fileUploadsList = upload1Mapper.selectUploadAll();
model.addAttribute("fileUploadsList", fileUploadsList);
return "/download.html";
}
//下载
@GetMapping("/downloadd")
public void download(Integer id, String openStyle, HttpServletResponse response) throws IOException {
Upload1 fileUpload = upload1Mapper.selectUpload(id);
// 获取全路径
// String globalPath = ResourceUtils.getURL("classpath:").getPath() + "static" + fileUpload.getPath() + "/";
String globalPath = fileUpload.getSavepath();
System.out.println(globalPath);
FileInputStream fis = new FileInputStream(new File(globalPath, fileUpload.getNewName()));
// 根据传过来的参数判断是下载,还是在线打开
if ("attachment".equals(openStyle)) {
// 并更新下载次数
// fileUpload.setDownCounts(fileUpload.getDownCounts() + 1);
// fileUploadService.updateFileDownCounts(id, fileUpload.getDownCounts());
// 以附件形式下载 点击会提供对话框选择另存为:
response.setHeader("content-disposition",
"attachment;filename=" + URLEncoder.encode(fileUpload.getName(), "utf-8"));
}
// 获取输出流
ServletOutputStream os = response.getOutputStream();
// 利用IO流工具类实现流文件的拷贝,(输出显示在浏览器上在线打开方式)
IOUtils.copy(fis, os);
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(os);
}
4、完整的Controller
package com.example.uploaddemo1.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.uploaddemo1.dao.Upload1Mapper;
import com.example.uploaddemo1.entity.Upload1;
@Controller
public class UploadController {
@Autowired
private Upload1Mapper upload1Mapper;
// @Autowired
// private Upload1 upload1;
@PostMapping("/upload")
public String upload(HttpSession session, @RequestParam("file") MultipartFile file, RedirectAttributes attributes)
throws IOException {
System.out.println("准备上传");
if (file.isEmpty()) {
attributes.addFlashAttribute("msg", "上传的文件不能为空");
return "";
}
// 获取原始文件名称
String originalFilename = file.getOriginalFilename();
System.out.println("原始文件名称==" + originalFilename);
// 获取文件后缀名
// String extension = "." + FilenameUtils.getExtension(originalFilename); //.jpg
// 获取新文件名称 命名:时间戳+UUID+后缀
String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString()
+ originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
// 获取资源路径 classpath的项目路径+/static/files classpath就是resources的资源路径
String path = ResourceUtils.getURL("classpath:").getPath() + "static/files/";
System.out.println("资源路径==" + path);
// 新建一个时间文件夹标识,用来分类
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// 全路径(存放资源的路径) 资源路径+时间文件夹标识
String dataDir = path + format;
System.out.println("全路径==" + dataDir);
// 全路径存放在文件类中,判断文件夹是否存在不存在就创建
File dataFile = new File(dataDir); // 也可以直接放进去进行拼接 File dataFile = new File(path,format);
if (!dataFile.exists()) {
dataFile.mkdirs();
}
// 文件上传至指定路径
file.transferTo(new File(dataFile, newFileName));
int b = upload1Mapper.insertUpload(originalFilename, dataDir, newFileName);
System.out.println(b);
if (b == 1) {
attributes.addFlashAttribute("msg", "保存成功!");
} else {
attributes.addFlashAttribute("msg", "保存失败!");
}
System.out.println("上传结束");
return "redirect:/downloads";
}
@GetMapping("/downloads")
public String fileAll(HttpSession session, Model model) {
List<Upload1> fileUploadsList = upload1Mapper.selectUploadAll();
model.addAttribute("fileUploadsList", fileUploadsList);
return "/download.html";
}
@GetMapping("/downloadd")
public void download(Integer id, String openStyle, HttpServletResponse response) throws IOException {
Upload1 fileUpload = upload1Mapper.selectUpload(id);
// 获取全路径
// String globalPath = ResourceUtils.getURL("classpath:").getPath() + "static" + fileUpload.getPath() + "/";
String globalPath = fileUpload.getSavepath();
System.out.println(globalPath);
FileInputStream fis = new FileInputStream(new File(globalPath, fileUpload.getNewName()));
// 根据传过来的参数判断是下载,还是在线打开
if ("attachment".equals(openStyle)) {
// 并更新下载次数
// 以附件形式下载 点击会提供对话框选择另存为:
response.setHeader("content-disposition",
"attachment;filename=" + URLEncoder.encode(fileUpload.getName(), "utf-8"));
}
// 获取输出流
ServletOutputStream os = response.getOutputStream();
// 利用IO流工具类实现流文件的拷贝,(输出显示在浏览器上在线打开方式)
IOUtils.copy(fis, os);
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(os);
}
}