實(shí)現(xiàn)步驟及效果呈現(xiàn)如下:
1.創(chuàng)建數(shù)據(jù)庫表:
表名:file_test
存儲后的數(shù)據(jù):
2.創(chuàng)建數(shù)據(jù)庫表對應(yīng)映射的實(shí)體類:
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
?* 文件實(shí)體類
?*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("file_test")
public class File {
????/**
?????* 主鍵id
?????*/
????@TableId(value = "id",type = IdType.AUTO)
????private Integer id;
????/**
?????* 文件名稱
?????*/
????@TableField("file_name")
????private String fileName;
????/**
?????* 文件路徑
?????*/
????@TableField("file_path")
????private String filePath;
????/**
?????* 上傳時(shí)間
?????*/
????@TableField("upload_time")
????private Date uploadTime;
}
- 創(chuàng)建數(shù)據(jù)訪問層Mapper(用來寫數(shù)據(jù)庫的增刪改查SQL)
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fm.model.File;
import org.apache.ibatis.annotations.Mapper;
/**
?* 數(shù)據(jù)庫映射
?* 集成了mybtis-plus??包含了常用的增刪改查方法
?*/
@Mapper
public interface FileMapper extends BaseMapper<File> {
}
- 創(chuàng)建業(yè)務(wù)層service
import com.baomidou.mybatisplus.extension.service.IService;
import com.fm.model.File;
import org.springframework.web.multipart.MultipartFile;
/**
?* 文件業(yè)務(wù)層
?* 集成了mybatis-plus ?里面包含了數(shù)據(jù)庫常用的增刪改成方法
?*/
public interface FileService extends IService<File> {
????void upload(MultipartFile file);
}
- 創(chuàng)建業(yè)務(wù)實(shí)現(xiàn)類serviceImpl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fm.mapper.FileMapper;
import com.fm.model.File;
import com.fm.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
/**
?* 文件業(yè)務(wù)實(shí)現(xiàn)層
?* 集成了mybatis-plus ?里面包含了數(shù)據(jù)庫常用的增刪改成方法
?*/
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {
????@Resource
????private FileMapper fileMapper;
????@Override
????public void upload(MultipartFile file) {
????????//獲取當(dāng)前項(xiàng)目所在根目錄
????????String rootDirectory = System.getProperty("user.dir");
????????//如果當(dāng)前項(xiàng)目根目錄不存在(file_manage文件存儲)文件夾,
????????// 會自動創(chuàng)建該文件夾用于存儲項(xiàng)目上傳的文件
????????java.io.File savaFile = new java.io.File(rootDirectory + "/file_manage項(xiàng)目文件存儲/" + file.getOriginalFilename());
????????if (!savaFile.getParentFile().exists()) {
????????????savaFile.getParentFile().mkdirs();
????????}
????????//如果當(dāng)前名稱的文件已存在則跳過
????????if (savaFile.exists()) {
????????????return;
????????}
????????try {
????????????savaFile.createNewFile();
????????????file.transferTo(savaFile);
????????} catch (IOException e) {
????????????e.printStackTrace();
????????}
????????File file1 = new File();
????????file1.setFileName(file.getOriginalFilename());
????????file1.setFilePath("/file_manage項(xiàng)目文件存儲/" + file.getOriginalFilename());
????????file1.setUploadTime(new Date());
????????fileMapper.insert(file1);
????}
}
- 創(chuàng)建接口層controller(用來寫上傳、下載、查詢列表、刪除接口)
import com.fm.model.File;
import com.fm.service.FileService;
import com.fm.util.FileUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
?* 文件接口層
?*/
@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {
????//文件實(shí)現(xiàn)層
????@Resource
????private FileService fileService;
????/**
?????* 文件列表
?????*/
????@RequestMapping(value = "/list", method = RequestMethod.GET)
????public List<File> list(
????) {
????????try {
????????????List<File> list = fileService.list();
????????????return list;
????????} catch (Exception e) {
????????????e.printStackTrace();
????????}
????????return null;
????}
????/**
?????* 上傳文件
?????*
?????* @param file
?????* @return
?????*/
????@RequestMapping(value = "/upload", method = RequestMethod.POST)
????public String upload(
????????????@RequestParam(value = "file") MultipartFile file//文件
????) {
????????try {
????????????fileService.upload(file);
????????????return "文件上傳成功!";
????????} catch (Exception e) {
????????????e.printStackTrace();
????????????return "文件上傳失??!";
????????}
????}
????/**
?????* 刪除文件
?????*
?????* @param fileId
?????* @return
?????*/
????@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
????public String delete(
????????????@RequestParam(value = "fileId") String fileId//文件
????) {
????????try {
????????????File file = fileService.getById(fileId);
????????????//獲取當(dāng)前項(xiàng)目所在根目錄
????????????String rootDirectory = System.getProperty("user.dir");
????????????java.io.File savaFile = new java.io.File(rootDirectory + file.getFilePath());
????????????//刪除保存的文件
????????????savaFile.delete();
????????????boolean b = fileService.removeById(fileId);
????????????if (b){
????????????????return "成功!";
????????????}
????????????return "失?。?/span>";
????????} catch (Exception e) {
????????????e.printStackTrace();
????????????return "失敗";
????????}
????}
????/**
?????* 下載文件
?????*/
????@RequestMapping(value = "/download", method = RequestMethod.GET)
????public void download(@RequestParam(value = "fileId") String fileId,
?????????????????????????HttpServletResponse response, HttpServletRequest request
????) {
????????try {
????????????File file = fileService.getById(fileId);
????????????if (file != null) {
????????????????//獲取當(dāng)前項(xiàng)目所在根目錄
????????????????String rootDirectory = System.getProperty("user.dir");
????????????????//調(diào)用自主實(shí)現(xiàn)的下載文件工具類中下載文件的方法
????????????????FileUtil.doDownloadFile(rootDirectory + file.getFilePath(), response, request);
????????????}
????????} catch (Exception e) {
????????????e.printStackTrace();
????????????System.out.println("下載文件出錯,錯誤原因:" + e);
????????}
????}
}
- 文件工具類(用來寫下載文件的方法)
/**
?* 文件工具類
?*/
public class FileUtil {
????/**
?????* 下載文件
?????* @param Path
?????* @param response
?????* @param request
?????*/
????public static void doDownloadFile(String Path, HttpServletResponse response, HttpServletRequest request) {
????????try {
????????????//關(guān)鍵點(diǎn),需要獲取的文件所在文件系統(tǒng)的目錄,定位準(zhǔn)確才可以順利下載文件
????????????String filePath = Path;
????????????File file = new File(filePath);
????????????//創(chuàng)建一個(gè)輸入流,將讀取到的文件保存到輸入流
????????????InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
????????????byte[] buffer = new byte[fis.available()];
????????????fis.read(buffer);
????????????fis.close();
????????????// 清空response
????????????response.reset();
????????????// 重要,設(shè)置response的Header
????????????response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
????????????response.setHeader("Content-Length", "" + file.length());
????????????//octet-stream是二進(jìn)制流傳輸,當(dāng)不知文件類型時(shí)都可以用此屬性
????????????response.setContentType("application/octet-stream");
????????????//跨域請求,*代表允許全部類型
????????????response.setHeader("Access-Control-Allow-Origin", "*");
????????????//允許請求方式
????????????response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
????????????//用來指定本次預(yù)檢請求的有效期,單位為秒,在此期間不用發(fā)出另一條預(yù)檢請求
????????????response.setHeader("Access-Control-Max-Age", "3600");
????????????//請求包含的字段內(nèi)容,如有多個(gè)可用哪個(gè)逗號分隔如下
????????????response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,Authorization, x-ui-request,lang");
????????????//訪問控制允許憑據(jù),true為允許
????????????response.setHeader("Access-Control-Allow-Credentials", "true");
????????????//創(chuàng)建一個(gè)輸出流,用于輸出文件
????????????OutputStream oStream = new BufferedOutputStream(response.getOutputStream());
????????????//寫入輸出文件
????????????oStream.write(buffer);
????????????oStream.flush();
????????????oStream.close();
????????} catch (Exception e) {
????????????System.out.println("下載日志文件出錯,錯誤原因:" + e);
????????}
????}
}
Pom文件依賴
<?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.3.12.RELEASE</version>
????????<relativePath/> <!-- lookup parent from repository -->
????</parent>
????<groupId>com.fm</groupId>
????<artifactId>file_manage</artifactId>
????<version>0.0.1-SNAPSHOT</version>
????<name>file_manage</name>
????<description>file_manage</description>
????<properties>
????????<java.version>22</java.version>
????</properties>
????<dependencies>
????????<dependency>
????????????<groupId>org.springframework.boot</groupId>
????????????<artifactId>spring-boot-starter-web</artifactId>
????????</dependency>
????????<dependency>
????????????<groupId>org.projectlombok</groupId>
????????????<artifactId>lombok</artifactId>
????????????<optional>true</optional>
????????</dependency>
????????<dependency>
????????????<groupId>org.springframework.boot</groupId>
????????????<artifactId>spring-boot-starter-test</artifactId>
????????????<scope>test</scope>
????????</dependency>
<!-- ???????mysql依賴-->
????????<dependency>
????????????<groupId>mysql</groupId>
????????????<artifactId>mysql-connector-java</artifactId>
????????????<version>8.0.29</version>
????????</dependency>
<!-- ???????jdbc依賴-->
????????<dependency>
????????????<groupId>org.springframework.boot</groupId>
????????????<artifactId>spring-boot-starter-jdbc</artifactId>
????????</dependency>
<!-- ???????mybatis-plus依賴-->
????????<dependency>
????????????<groupId>com.baomidou</groupId>
????????????<artifactId>mybatis-plus-boot-starter</artifactId>
????????????<version>3.5.1</version>
????????</dependency>
<!-- ???????JSON依賴-->
????????<dependency>
????????????<groupId>com.alibaba</groupId>
????????????<artifactId>fastjson</artifactId>
????????????<version>1.2.70</version>
????????</dependency>
????</dependencies>
????<build>
????????<plugins>
????????????<plugin>
????????????????<groupId>org.springframework.boot</groupId>
????????????????<artifactId>spring-boot-maven-plugin</artifactId>
????????????????<configuration>
????????????????????<excludes>
????????????????????????<exclude>
????????????????????????????<groupId>org.projectlombok</groupId>
????????????????????????????<artifactId>lombok</artifactId>
????????????????????????</exclude>
????????????????????</excludes>
????????????????</configuration>
????????????</plugin>
????????</plugins>
????</build>
</project>
yml配置文件:
#數(shù)據(jù)庫連接配置
spring:
??datasource:
????driver-class-name: com.mysql.cj.jdbc.Driver
????url: jdbc:mysql://localhost:3306/file_test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
????username: root
????password:
??jackson:
????date-format: yyyy-MM-dd HH:mm:ss
????# ???joda-date-time-format: yyyy-MM-dd HH:mm:ss
????time-zone: GMT+8
??thymeleaf:
????prefix: classpath:/static
????suffix: .html
????cache: false
#啟動端口
server:
??port: 8100
Html前端靜態(tài)頁面(內(nèi)置在springboot項(xiàng)目中可直接運(yùn)行):
<!DOCTYPE html>
<head>
????<meta charset="UTF-8">
</head>
<html lang="en">
<body>
<div id="app">
????<div class="container-fluid">
????????<!--標(biāo)題行-->
????????<div class="row">
????????????<div align="center" class="col-sm-6 col-sm-offset-3"><button style="font-size: 18px;float: right" href="" class="btn btn-info btn-sm" @click.prevent="uploadFile()">上傳文件</button><h1 class="text-center">文件列表</h1></div>
????????</div>
????????<!--數(shù)據(jù)行-->
????????<div class="row">
????????????<div class="col-sm-10 col-sm-offset-1">
????????????????<!--列表-->
????????????????<table class="table table-striped table-bordered" style="margin-top: 10px;">
????????????????????<tr>
????????????????????????<td align="center" style="font-size: 18px;">文件名稱</td>
????????????????????????<td align="center" style="font-size: 18px;">文件路徑</td>
????????????????????????<td align="center" style="font-size: 18px;">上傳時(shí)間</td>
????????????????????????<td align="center" style="font-size: 18px;">操作</td>
????????????????????</tr>
????????????????????<tr v-for="user in list">
????????????????????????<td style="font-size: 18px;">{{user.fileName}}</td>
????????????????????????<td style="font-size: 18px;">{{user.filePath}}</td>
????????????????????????<td style="font-size: 18px;">{{user.uploadTime}}</td>
????????????????????????<td>
????????????????????????????<button style="font-size: 18px;" href=" " class="btn btn-info btn-sm" @click="deleteFile(user.id)">刪除</button>
????????????????????????????<a style="font-size: 18px;" href=" " class="btn btn-info btn-sm" @click="downloadFile(user.id)">下載</a>
????????????????????????</td>
????????????????????</tr>
????????????????</table>
????????????</div>
????????</div>
????</div>
</div>
<!-- 彈出選擇文件表單 -->
<div id="my_dialog" class="my-dialog" style="display: none">
????<h3>需要上傳的文件</h3>
????<form id="form1" action="http://localhost:8100/file/upload" target="form1" method="post" enctype="multipart/form-data">
????????<input type="file" name="file" accept=".jpg,.png,.gif">
????????<button type="button" style="font-size: 18px;" onclick="upload()">提交</button>
????????<button type="button" style="font-size: 18px;" onclick="cancelFile()">取消</button>
????</form>
</div>
<style type="text/css">
????.container-fluid {
????????width: 650px;
????//height: 200px;
????//background-color: orchid;
????????position: absolute;
????????top: 0;
????????left: 0;
????????right: 0;
????????bottom: 0;
????????margin: auto;
????}
????.my-dialog {
????????width: 300px;
????//height: 200px;
????//background-color: orchid;
????????position: absolute;
????????top: 0;
????????left: 0;
????????right: 0;
????????bottom: 0;
????????margin: auto;
????}
</style>
</body>
</html>
<!--引入jquery-->
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<!--引入axios-->
<script src="js/axios.min.js"></script>
<!--引入vue-->
<script src="js/vue.js"></script>
<script>
????var app = new Vue({
????????el: "#app",
????????data:{
????????????msg:"vue 生命周期",
????????????list:[], //定義一個(gè)list空數(shù)組,用來存貯所有文件的信息
????????},
????????methods:{
????????????uploadFile(){ ?//文件選擇
????????????????/*懸浮窗口的顯示,需要將display變成block*/
????????????????document.getElementById("my_dialog").style.display = "block";
????????????????/*將列表隱藏*/
????????????????document.getElementById("app").style.display = "none";
????????????},
????????????deleteFile(id){
????????????????/*alert("刪除!");*/
????????????????console.log("打印數(shù)據(jù)"+id);
????????????????axios.delete('http://localhost:8100/file/delete',{
????????????????????params:{
????????????????????????fileId:id,
????????????????????},
????????????????}).then(response=>{
????????????????????console.log("回調(diào)--->>>"+response.data);
????????????????????if (response.data == "成功!") {
????????????????????????alert("刪除成功!");
????????????????????????//跳轉(zhuǎn)到顯示頁面
????????????????????????//document.referrer 前一個(gè)頁面的URL ?返回并刷新頁面
????????????????????????location.replace(document.referrer);
????????????????????} else {
????????????????????????alert("刪除失??!");
????????????????????????//document.referrer 前一個(gè)頁面的URL ?返回并刷新頁面
????????????????????????location.replace(document.referrer);
????????????????????}
????????????????})
????????????},
????????????downloadFile(id){
????????????????window.open("http://localhost:8100/file/download?fileId="+id);
????????????},
????????},
????????computed:{
????????},
????????created(){ //執(zhí)行?data methods computed 等完成注入和校驗(yàn)
????????????//發(fā)送axios請求
????????????axios.get("http://localhost:8100/file/list").then(res=>{
????????????????console.log(res.data);
????????????????this.list = res.data;
????????????}); //es6 箭頭函數(shù) 注意:箭頭函數(shù)內(nèi)部沒有自己this ?簡化?function(){} //存在自己this
????????},
????});
????cancelFile=function(){ //返回首頁
????????/*浮窗口隱藏*/
????????document.getElementById("my_dialog").style.display = "none";
????????/*將列表顯示*/
????????document.getElementById("app").style.display = "block";
????};
????function upload() {
????????/*alert('文件上傳成功!');*/
????????$("#form1").submit();
????????//document.referrer 前一個(gè)頁面的URL ?返回并刷新頁面
????????location.replace(document.referrer);
????}
</script>
運(yùn)行效果:
上傳文件:
選擇文件:
提交成功后;
列表新增一條數(shù)據(jù):
點(diǎn)擊下載選擇保存位置:
點(diǎn)擊刪除后:
點(diǎn)擊確定文件列表刪除一條數(shù)據(jù):
html靜態(tài)頁面需要js等文件,會放在完整項(xiàng)目里面,有需要的朋友自取。
??????
完整素材及全部代碼
? ?代碼已上傳csdn,0積分下載,覺得這片博文有用請留下你的點(diǎn)贊,有問題的朋友可以一起交流討論。文章來源:http://www.zghlxwxcb.cn/news/detail-861765.html
https://download.csdn.net/download/xuezhe5212/89238404
?文章來源地址http://www.zghlxwxcb.cn/news/detail-861765.html
到了這里,關(guān)于Springboot + MySQL + html 實(shí)現(xiàn)文件的上傳、存儲、下載、刪除的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!