1. 功能概述
将文件从本地上传到后端,因为文件过大,采用分片上传的方式,其中主要包括
检查文件(作为进度条的主要方法)
分片上传(进行上传文件)
2. 逻辑思路
(1)点击上传文件
(2)获取文件的md5值
(3)拿md5和文件名字进行匹配当前上传的文件
(4)检查接口:返回已经上传的文件大小,后续上传从此位移开始
(5)当返回的文件大小与上传的文件大小相同的时候完成分片上传并进行之后个人的业务逻辑
3.基础代码
3.1 原生input标签实现上传
<input type="file" @change="handleFileUpload" accept=".zip,.rar" ref="fileInput" />
3.2 获取文件的MD5
// 引入第三发依赖包
import SparkMD5 from "spark-md5";
/**
* 获取文件的MD5数值
* @param {*} file
*/
getUploadFileMD5(file) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = () => {
const arrayBuffer = fileReader.result;
const md5Hash = SparkMD5.ArrayBuffer.hash(arrayBuffer);
resolve(md5Hash);
};
fileReader.onerror = (error) => {
reject(error);
};
fileReader.readAsArrayBuffer(file);
});
},
3.3 上传文件
async handleFileUpload(e) {
this.file = e.target.files[0];
if (!this.file) return;
// 获取MD5
this.fileForm.md5 = await this.getUploadFileMD5(this.file);
if (this.fileForm.md5) {
// 执行上传到后台方法
this.uploadFile(this.file);
}
},
3.4 上传文件到后台
async uploadFile(file) {
// 检查文件 偏移量 未添加断点重传
let offset = await this.uploadCheck(this.fileForm);
// 1.后台返回的文件大小与当前文件大小相同的时候执行业务逻辑
if (offset === file.size) {
// 个人的业务逻辑
// this.pulbishImage();
return;
}
// 2.不相同的时候执行切片上传 eachSize: 5 * 1024 * 1024, 每一个切片的大小
// 当前第几个切片
const startChunks = Math.ceil(offset / this.eachSize);
// 总切片
const totalChunks = Math.ceil(file.size / this.eachSize);
for (let currentChunk = startChunks; currentChunk < totalChunks; currentChunk++) {
// 文件切片
const start = currentChunk * this.eachSize;
const end = Math.min(start + this.eachSize, file.size);
// 切片之后文件大小
const blobSlice = file.slice(start, end);
try {
let data = await this.uploadFragmentation({
md5: this.fileForm.md5,
file: blobSlice,
offset: start,
fileName: file.name,
});
if (data < file.size && data !== 0) {
this.percentage = Math.min(((data / file.size) * 100).toFixed(2), 100);
}
if (data === file.size) {
// 执行完之后判断文件相同执行业务逻辑
this.pulbishImage();
}
} catch (error) {
console.error("Error uploading chunk:", error);
return;
}
}
},
4. 完整代码
<template>
<el-dialog
title="影像添加"
:visible.sync="dialogVisible"
width="24%"
:before-close="handleClose"
:modal-append-to-body="true"
:append-to-body="true"
>
<div class="contents">
<el-radio-group v-model="formtype">
<el-radio label="本地数据上传"></el-radio>
<el-radio label="服务器数据扫描"></el-radio>
</el-radio-group>
<el-row>
<el-col :span="6"> 影像名称 </el-col>
<el-col :span="18">
<el-input v-model="imageData.name"></el-input>
</el-col>
</el-row>
<el-row>
<el-col :span="6"> 影像数据 </el-col>
<el-col :span="18">
<el-input v-model="fileForm.fileName"></el-input>
<input
type="file"
@change="handleFileUpload"
accept=".tif"
ref="fileInput"
v-show="false"
/>
<div class="choice" @click="upload">选择</div>
</el-col>
</el-row>
<el-row>
<el-col :span="6"> 数据类型 </el-col>
<el-col :span="18">
<el-select
v-model="createForm.datatype"
clear
placeholder="请选择"
collapse-tags
@change="handleDataType"
clearable
>
<el-option label="选项1" :value="1"></el-option>
<el-option label="选项2" :value="2"></el-option>
<el-option label="选项3" :value="3"></el-option>
</el-select>
</el-col>
</el-row>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="$emit('toggle')">取 消</el-button>
<el-button type="primary" @click="confirm">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
import SparkMD5 from "spark-md5";
import http from "@/service/interface";
export default {
data() {
return {
formtype: "本地数据上传",
createForm: {
images: "",
datatype: "",
},
file: null,
eachSize: 5 * 1024 * 1024,
fileForm: {
fileName: "",
md5: "",
},
imageData: {
name: "",
key: null,
type: "3",
props: {
url:
"map/wmts/1.0.0/917bf85d058528f892fd85a76c39f345/default/getTile/{z}/{x}/{y}",
extent: [
111.76419936300005,
112.03969936300004,
29.28138836200003,
29.73343836200003,
],
format: "xyz",
properties: {
bands: 3,
"product-level": "",
"image-gsd": 0.00001,
},
images: [
"Y:\\03-数据资料\\PIE-NRSAI2.0_DATA\\程序上传\\dev\\917bf85d058528f892fd85a76c39f345-Q3_jss.tif",
],
},
pid: null,
isEdit: true,
},
};
},
props: ["dialogVisible"],
components: {},
methods: {
handleClose() {
this.$emit("toggle");
},
handleDataType(data) {
console.log(data, "选中的数据");
},
confirm() {
this.$emit("addImageData", this.imageData);
},
upload() {
this.$refs.fileInput.click();
},
async handleFileUpload(e) {
this.file = e.target.files[0];
if (!this.file) return;
this.fileForm.fileName = this.file.name;
this.fileForm.md5 = await this.getUploadFileMD5(this.file);
if (this.fileForm.md5) {
this.uploadFile(this.file);
}
},
/**
* 获取文件的MD5数值
* @param {*} file
*/
getUploadFileMD5(file) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = () => {
const arrayBuffer = fileReader.result;
const md5Hash = SparkMD5.ArrayBuffer.hash(arrayBuffer);
resolve(md5Hash);
};
fileReader.onerror = (error) => {
reject(error);
};
fileReader.readAsArrayBuffer(file);
});
},
//上传文件
async uploadFile(file) {
// 检查文件 偏移量 未添加断点重传
let offset = await this.uploadCheck(this.fileForm);
if (offset === file.size) {
this.pulbishImage();
return;
}
// 当前第几个切片
const startChunks = Math.ceil(offset / this.eachSize);
// 总切片
const totalChunks = Math.ceil(file.size / this.eachSize);
for (let currentChunk = startChunks; currentChunk < totalChunks; currentChunk++) {
// 文件切片
const start = currentChunk * this.eachSize;
const end = Math.min(start + this.eachSize, file.size);
// 切片之后文件大小
const blobSlice = file.slice(start, end);
try {
let data = await this.uploadFragmentation({
md5: this.fileForm.md5,
file: blobSlice,
offset: start,
fileName: file.name,
});
if (data < file.size && data !== 0) {
this.percentage = Math.min(((data / file.size) * 100).toFixed(2), 100);
}
if (data === file.size) {
this.pulbishImage();
}
} catch (error) {
console.error("Error uploading chunk:", error);
return;
}
}
},
async uploadCheck(params) {
const { md5, fileName } = params;
let res = await http.uploadCheck({ md5, name: fileName });
return res.data;
},
async uploadFragmentation(params) {
let res = await http.uploadFragmentation(params);
return res.data;
},
async pulbishImage() {
let res = await http.pulbishImage(this.fileForm);
console.log(res, "发布影像服务");
if (res.status == 200) {
this.$emit("addImageData");
} else {
this.$message.error("上传影像出现问题,请及时核查");
}
},
},
mounted() {},
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog {
.contents {
background: #131314;
width: calc(100% - 44px);
padding-bottom: 24px;
padding-left: 44px;
.el-radio-group {
line-height: 53px;
height: 30px;
}
.el-radio {
color: #ffffff;
}
.el-row {
display: flex;
flex-direction: row;
margin-top: 16px;
.el-col {
height: 32px;
line-height: 32px;
font-size: 14px;
font-family: Source Han Sans CN, Source Han Sans CN-400;
font-weight: 400;
text-align: LEFT;
color: #b3b5bd;
}
.el-input__icon {
line-height: 32px;
}
.el-input__inner {
width: 243px;
height: 32px;
background: rgba(32, 33, 36, 0.7);
border: 1px solid #363c4e;
border-radius: 2px;
color: #ffffff;
}
}
.choice {
width: 50px;
height: 35px;
cursor: pointer;
background: rgba(var(--theme_vue_background_rgb), 0.8);
border-radius: 2px;
text-align: center;
line-height: 35px;
font-size: 15px;
font-family: Source Han Sans CN-Regular;
font-weight: 400;
color: var(--theme_header_text_color1);
position: absolute;
top: 0px;
right: 9px;
}
}
.el-dialog__header {
height: 52px;
background: #212224;
border-radius: 2px 2px 0px 0px;
padding: 0px;
.el-dialog__title {
font-size: 15px;
font-family: Source Han Sans CN, Source Han Sans CN-400;
font-weight: 400;
text-align: LEFT;
color: #ffffff;
line-height: 52px;
padding-left: 21px;
}
.el-dialog__headerbtn {
width: 28px;
height: 28px;
background: #303134;
border-radius: 2px;
font-size: 18px;
top: 13px;
.el-dialog__close {
color: #ffffff;
}
}
}
.el-dialog__body {
padding: 0;
}
.el-dialog__footer {
padding: 0;
background: #131314;
border-top: 1px solid #2c2c2e;
display: flex;
flex-direction: row;
justify-content: center;
}
}
</style>
文章来源地址https://www.toymoban.com/news/detail-833281.html
文章来源:https://www.toymoban.com/news/detail-833281.html
到了这里,关于vue(前端):大文件分片上传(包括如何获取文件MD5、逻辑注释讲解)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!