SpringBoot中⼤⽂件(分⽚上传)断点续传与极速秒传功能的实现1.创建SpringBoot项⽬
本项⽬采⽤springboot + mybatis-plus +jquery +thymeleaf组成
2.项⽬流程图
3.在pom中添加以下依赖
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--⽂件上传依赖-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql的依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- mybatis-plus依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
4.在application.properties配置⽂件中
server.port=8000
#设置上传图⽚的路径
file.basepath=D:/BaiduNetdiskDownload/
# 设置单个⽂件⼤⼩
spring.servlet.multipart.max-file-size= 50MB
# 设置单次请求⽂件的总⼤⼩
spring.servlet.multipart.max-request-size= 50MB
##设置要连接的mysql数据库
spring.datasource.sql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
5.在数据库创建表
create table file
(
id INTEGER primary key AUTO_INCREMENT comment 'id',
path varchar(100) not null COMMENT '相对路径',
name varchar(100) COMMENT '⽂件名',
suffix varchar(10) COMMENT '⽂件后缀',
size int COMMENT '⽂件⼤⼩|字节B',
created_at BIGINT(20) COMMENT '⽂件创建时间',
shard_total int COMMENT '分⽚总数',
file_key varchar(100) COMMENT '⽂件标识'
)
6.创建实体类
import batisplus.annotation.IdType;
import batisplus.annotation.TableId;
import batisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName(value = "file")
public class FileDTO {
/**
* id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 相对路径
*/
private String path;
/**
* ⽂件名
*/
private String name;
/**
* 后缀
*/
private String suffix;
/**
* ⼤⼩|字节B
*/
private Integer size;
/**
* 创建时间
*/
private Long createdAt;
/
**
* 修改时间
*/
private Long updatedAt;
/**
* 已上传分⽚
*/
private Integer shardIndex;
/**
* 分⽚⼤⼩|B
*/
private Integer shardSize;
/**
* 分⽚总数
*/
private Integer shardTotal;
/**
* ⽂件标识
*/
private String fileKey;
}
7.创建mapper
import apper.BaseMapper;
ample.ity.FileDTO;
import org.springframework.stereotype.Repository;
@Repository
public interface FileMapper extends BaseMapper<FileDTO> {
}
8.创建service
import ditions.query.LambdaQueryWrapper; import ditions.query.QueryWrapper;
ample.demo.upload.dao.FileMapper;
ample.ity.FileDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FileService {
@Autowired
private FileMapper fileMapper;
//保存⽂件
public void save(FileDTO file1){
//根据数据库的⽂件标识来查询当前视频是否存在
LambdaQueryWrapper<FileDTO> lambda = new QueryWrapper<FileDTO>().lambda(); lambda.eq(FileDTO::FileKey());
List<FileDTO> fileDTOS = fileMapper.selectList(lambda);
//如果存在就话就修改
if(fileDTOS.size()!=0){
//根据key来修改
LambdaQueryWrapper<FileDTO> lambda1 = new QueryWrapper<FileDTO>().lambda(); lambda1.eq(FileDTO::FileKey());
fileMapper.update(file1,lambda1);
}else
{
//不存在就添加
fileMapper.insert(file1);
}
}
LambdaQueryWrapper<FileDTO> lambda = new QueryWrapper<FileDTO>().lambda(); lambda.eq(FileDTO::getFileKey,key);
List<FileDTO> dtos = fileMapper.selectList(lambda);
return dtos;
}
}
9.创建utils
import lombok.Data;
/**
* 统⼀返回值
*
* @author zhangshuai
*
*/
@Data
public class Result {
// 成功状态码
public static final int SUCCESS_CODE = 200;
// 请求失败状态码
public static final int FAIL_CODE = 500;
// 查⽆资源状态码
public static final int NOTF_FOUNT_CODE = 404;
// ⽆权访问状态码
public static final int ACCESS_DINE_CODE = 403;
/**
* 状态码
*/
private int code;
/**
* 提⽰信息
*/
private String msg;
/**
* 数据信息
*/
private Object data;
/**
* 请求成功
*
* @return
*/
springboot原理pdfpublic static Result ok() {
Result r = new Result();
r.setCode(SUCCESS_CODE);
r.setMsg("请求成功!");
r.setData(null);
return r;
}
/**
* 请求失败
*
* @return
*/
public static Result fail() {
Result r = new Result();
r.setCode(FAIL_CODE);
r.setMsg("请求失败!");
r.setData(null);
return r;
}
/**
* 请求成功,⾃定义信息
*
* @param msg
* @return
*/
public static Result ok(String msg) {
Result r = new Result();
r.setCode(SUCCESS_CODE);
r.setMsg(msg);
r.setData(null);
return r;
}
/**
* 请求失败,⾃定义信息
*
* @param msg
* @return
*/
public static Result fail(String msg) {
Result r = new Result();
r.setCode(FAIL_CODE);
r.setMsg(msg);
r.setData(null);
return r;
}
/**
* 请求成功,⾃定义信息,⾃定义数据
*
* @param msg
* @return
*/
public static Result ok(String msg, Object data) {
Result r = new Result();
r.setCode(SUCCESS_CODE);
r.setMsg(msg);
r.setData(data);
return r;
}
/**
* 请求失败,⾃定义信息,⾃定义数据
*
* @param msg
Result r = new Result();
r.setCode(FAIL_CODE);
r.setMsg(msg);
r.setData(data);
return r;
}
public Result code(Integer code){
this.setCode(code);
return this;
}
public Result data(Object data){
this.setData(data);
return this;
}
public Result msg(String msg){
this.setMsg(msg);
return this;
}
}
10.创建controller
ample.ity.FileDTO;
ample.demo.upload.service.FileService;
ample.demo.upload.utils.Result;
slf4j.Slf4j;
import org.apachemons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/file")
@Slf4j
public class FileController {
@Autowired
FileService fileService;
public static final String BUSINESS_NAME = "普通分⽚上传";
/
/ 设置图⽚上传路径
@Value("${file.basepath}")
private String basePath;
@RequestMapping("/show")
public String show(){
return "file";
}
/**
* 上传
* @param file
* @param suffix
* @param shardIndex
* @param shardSize
* @param shardTotal
* @param size
* @param key
* @return
* @throws IOException
* @throws InterruptedException
*/
@RequestMapping("/upload")
@ResponseBody
public String upload(MultipartFile file,
String suffix,
Integer shardIndex,
Integer shardSize,
Integer shardTotal,
Integer size,
String key
) throws IOException, InterruptedException {
log.info("上传⽂件开始");
//⽂件的名称
String name = UUID.randomUUID().toString().replaceAll("-", "");
/
/ 获取⽂件的扩展名
String ext = OriginalFilename());
//设置图⽚新的名字
String fileName = new StringBuffer().append(key).append(".").append(suffix).toString(); // course\6sfSqfOwzmik4A4icMYuUe.mp4 //这个是分⽚的名字
String localfileName = new StringBuffer(fileName)
.append(".")
.append(shardIndex)
.toString(); // course\6sfSqfOwzmik4A4icMYuUe.mp4.1
// 以绝对路径保存重名命后的图⽚
File targeFile=new File(basePath,localfileName);
//上传这个图⽚
//数据库持久化这个数据
FileDTO file1=new FileDTO();
file1.setPath(basePath+localfileName);
file1.setName(name);
file1.setSuffix(ext);
file1.setSize(size);
file1.setCreatedAt(System.currentTimeMillis());
file1.setUpdatedAt(System.currentTimeMillis());
file1.setShardIndex(shardIndex);
file1.setShardSize(shardSize);
file1.setShardTotal(shardTotal);
file1.setFileKey(key);
//插⼊到数据库中
//保存的时候去处理⼀下这个逻辑
fileService.save(file1);
//判断当前是不是最后⼀个分页如果不是就继续等待其他分页合并分页
if(shardIndex .equals(shardTotal) ){
file1.setPath(basePath+fileName);
}
@RequestMapping("/check")
@ResponseBody
public Result check(String key){
List<FileDTO> check = fileService.check(key);
//如果这个key存在的话那么就获取上⼀个分⽚去继续上传
if(check.size()!=0){
return Result.ok("查询成功",(0));
}
return Result.fail("查询失败,可以添加");
}
/**
* @author fengxinglie
* 合并分页
*/
private void merge(FileDTO fileDTO) throws FileNotFoundException, InterruptedException {
//合并分⽚开始
log.info("分⽚合并开始");
String path = Path(); //获取到的路径没有.1 .2 这样的东西
//截取视频所在的路径
path = place(basePath,"");
Integer shardTotal= ShardTotal();
File newFile = new File(basePath + path);
FileOutputStream outputStream = new FileOutputStream(newFile,true); // ⽂件追加写⼊
FileInputStream fileInputStream = null; //分⽚⽂件
byte[] byt = new byte[10 * 1024 * 1024];
int len;
try {
for (int i = 0; i < shardTotal; i++) {
// 读取第i个分⽚
fileInputStream = new FileInputStream(new File(basePath + path + "." + (i + 1))); // course\6sfSqfOwzmik4A4icMYuUe.mp4.1 while ((len = ad(byt)) != -1) {
outputStream.write(byt, 0, len);
}
}
} catch (IOException e) {
<("分⽚合并异常", e);
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
outputStream.close();
log.info("IO流关闭");
} catch (Exception e) {
<("IO流关闭", e);
}
}
log.info("分⽚结束了");
//告诉java虚拟机去回收垃圾⾄于什么时候回收这个取决于虚拟机的决定
<();
//等待100毫秒等待垃圾回收去回收完垃圾
Thread.sleep(100);
log.info("删除分⽚开始");
for (int i = 0; i < shardTotal; i++) {
String filePath = basePath + path + "." + (i + 1);
File file = new File(filePath);
boolean result = file.delete();
log.info("删除{},{}", filePath, result ? "成功" : "失败");
}
log.info("删除分⽚结束");
}
}
11.创建html页⾯
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script src="cdn.bootcdn/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="/md5.js"></script>
<script type="text/javascript" src="/tool.js"></script>
<script type="text/javascript">
//上传⽂件的话得单独出来
function test1(shardIndex) {
console.log(shardIndex);
//永安⾥from表单提交
var fd = new FormData();
//获取表单中的file
var file=$('#inputfile').get(0).files[0];
/
/⽂件分⽚以20MB去分⽚
var shardSize = 20 * 1024 * 1024;
//定义分⽚索引
var shardIndex = shardIndex;
//定义分⽚的起始位置
var start = (shardIndex-1) * shardSize;
//定义分⽚结束的位置 file哪⾥来的?
var end = Math.min(file.size,start + shardSize);
//从⽂件中截取当前的分⽚数据
var fileShard = file.slice(start,end);
//分⽚的⼤⼩
var size = file.size;
//总⽚数
var shardTotal = il(size / shardSize);
//⽂件的后缀名
var fileName = file.name;
var suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length).toLowerCase();
//把视频的信息存储为⼀个字符串
var filedetails=file.name+file.pe+file.lastModifiedDate;
//使⽤当前⽂件的信息⽤md5加密⽣成⼀个key 这个加密是根据⽂件的信息来加密的如果相同的⽂件加的密还是⼀样的
var key = hex_md5(filedetails);
var key10 = parseInt(key,16);
//把加密的信息转为⼀个64位的
var key62 = Tool._10to62(key10);
//前⾯的参数必须和controller层定义的⼀样
fd.append('file',fileShard);
fd.append('suffix',suffix);
fd.append('shardIndex',shardIndex);
fd.append('shardSize',shardSize);
fd.append('shardTotal',shardTotal);
fd.append('size',size);
fd.append("key",key62)
$.ajax({
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论