分页组件
<template>
<div>
<el-pagination
:background="background"
:current-page.sync="currentPage"
:page-size.sync="pageSize"
:layout="layout"
:page-sizes="pageSizes"
:total="total"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
/>
</div>
</template>
<script>
export default {
name: 'Pagination',
props: {
total: {
required: true,
type: Number
},
page: {
type: Number,
default: 1
},
limit: {
type: Number,
default: 20
},
pageSizes: {
type: Array,
default() {
return [5, 10, 20, 30, 50]
}
},
layout: {
type: String,
default: 'total, sizes, prev, pager, next, jumper'
},
background: {
type: Boolean,
default: true
},
},
computed: {
currentPage: {
get() {
return this.page
},
set(val) {
this.$emit('update:page', val)
}
},
pageSize: {
get() {
return this.limit
},
set(val) {
this.$emit('update:limit', val)
}
}
},
methods: {
handleSizeChange(val) {
this.$emit('pagination', {page: 1, limit: val})
},
handleCurrentChange(val) {
this.$emit('pagination', {page: val, limit: this.pageSize})
}
}
}
</script>
父组件使用分页组件
data() {
return {
myToDoList: [],
queryParams: {
demandName: '',
hardwareModel: '',
manager: '',
state: '',
pageNum: 1,
pageSize: 5
},
total: 0,
}
},
mounted() {
this.getMyToDoList()
},
methods: {
handleSelectionChange(val) {
console.log(val)
this.queryParams.pageNum = val.page
this.queryParams.pageSize = val.limit
this.getMyToDoList()
},
selectMyToDoList() {
this.queryParams.pageNum = 1
this.getMyToDoList()
},
async getMyToDoList() {
const request = this.queryParams
console.log('请求参数', request)
const res = await getMyToDoList(request)
console.log('我的待办', res)
const myToDoList = res.data.data.myToDoList
this.myToDoList = myToDoList.content
this.total = myToDoList.totalNum
this.queryParams.pageNum = myToDoList.pageNum
this.queryParams.pageSize = myToDoList.pageSize
},
}
上传文件组件
<template>
<div class="Upload">
<!-- <el-dialog title="附件上传" :visible.sync="visible" width="800px" :close-on-click-modal="false" @close="cancel">-->
<div class="upload-file">
<!--
:action="action"
:before-upload="handleBeforeUpload"
:file-list="fileList"
:limit="3"
multiple
:accept="accept"
:on-error="handleUploadError"
:on-exceed="handleExceed"
:on-success="handleUploadSuccess"
:on-change="handChange"
:http-request="httpRequest"
:show-file-list="true"
:auto-upload="false"
class="upload-file-uploader"
ref="upload"
-->
<el-upload
:action="action"
:before-upload="handleBeforeUpload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:limit="limit"
multiple
:accept="accept"
:on-error="handleUploadError"
:on-exceed="handleExceed"
:on-success="handleUploadSuccess"
:on-change="handChange"
:http-request="httpRequest"
:show-file-list="true"
:auto-upload="false"
class="upload-file-uploader"
ref="upload"
>
<!-- 上传按钮 -->
<el-button slot="trigger" size="mini" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" :disabled="fileList&&fileList.length < 1" size="small" type="success"
@click="submitUpload">上传到服务器
</el-button>
<!-- 上传提示 -->
<div class="el-upload__tip" slot="tip" v-if="isShowTip">
请上传
<template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
<template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
的文件
</div>
</el-upload>
<!-- 文件列表 -->
<transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear"
tag="ul">
<li v-for="(file, index) in fileList" :key="file.id"
class="el-upload-list__item ele-upload-list__item-content">
</div>
</template>
<script>
import {uploadAttachment, downloadAttachmentByID, deleteAttachmentByID} from '@/api/mmis/index.js'
export default {
name: "Upload",
props: {
value: [String, Object, Array],
fileSize: {
type: Number,
default: 2,
},
fileType: {
type: Array,
default: () => [".jpg", ".jpeg", ".png", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".txt", ".pdf", ".xml", ".XML"],
},
isShowTip: {
type: Boolean,
default: false
},
limit: {
type: Number,
default: 5
},
requestParams: {},
fileList: [],
},
data() {
return {
visible: false,
accept: '',
action: 'action'
}
},
watch: {
"fileList": {
handler(newData) {
console.log('fileList', newData)
},
deep: true,
}
},
mounted() {
this.fileType.forEach(el => {
this.accept += el
this.accept += ','
})
},
methods: {
submitUpload() {
console.log('上传', this.fileList)
if (this.fileList.length <= 0) {
return false
}
this.$refs.upload.submit()
},
httpRequest(param) {
console.log("uploadFile", param.file);
console.log("requestParams", this.requestParams.itemName, this.requestParams.sourceNode);
const formdata = new FormData();
formdata.append("uploadFile", param.file);
for (let i in this.requestParams) {
formdata.append(i, this.requestParams[i]);
}
uploadAttachment(formdata).then(res => {
console.log(res)
if (res.data.code === 200) {
this.$emit("getfileList", res.data.data)
param.onSuccess()
this.$refs.upload.clearFiles()
}
}).catch((err) => {
})
},
handleUploadError(err) {
this.$message.error("上传失败, 请重试");
},
handleUploadSuccess(res, file) {
this.$message.success("上传成功");
this.cancel()
},
async handlePreview(file) {
console.log('上传的file', file)
console.log('fileList', this.fileList)
const res = await downloadAttachmentByID({id: file.id})
console.log(res);
const blob = new Blob([res.data])
const a = document.createElement('a')
const href = window.URL.createObjectURL(blob)
a.href = href
a.download = file.name
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(href)
},
async handleRemove(file) {
console.log(file)
if (file.status == "success") {
console.log("删除的文件id------------", file.id);
const request = {id: file.id};
console.log(request);
const res = await deleteAttachmentByID(request);
console.log('deleteres', res)
if (res.data.code == 200) {
this.$message.success("文件删除成功");
this.$emit('delfileList', file.id)
}
}
},
handleBeforeUpload(file) {
let fileExtension = "";
if (file.name.lastIndexOf(".") > -1) {
fileExtension = file.name.slice(file.name.lastIndexOf("."));
}
const isTypeOk = this.fileType.some((type) => {
if (file.type.indexOf(type) > -1) return true;
if (fileExtension && fileExtension.indexOf(type) > -1) return true;
return false;
});
if (!isTypeOk) {
this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
return false;
}
if (this.fileSize) {
const isLt = file.size / 1024 / 1024 < this.fileSize;
if (!isLt) {
this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
return false;
}
}
return true;
},
handleExceed() {
this.$message.error(`允许上传最多${this.limit}个文件`);
},
handChange(file, fileList) {
this.fileList = fileList
},
getFileName(name) {
if (name.lastIndexOf("/") > -1) {
return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
} else {
return "";
}
},
}
}
</script>
<style scoped>
</style>
父组件使用
<template>
<el-form-item label="性能指标:" prop="performanceIndexList">
<Upload ref="fileUploadDialog" :request-params="{itemName:'性能指标',sourceNode:'需求申请'}"
:fileList.sync="applyForm.performanceIndexList"
@getfileList="getPerformanceList"
@delfileList="delPerformanceList"></Upload>
</el-form-item>
</template>
methods:{
getPerformanceList(data) {
this.applyForm.performanceIndexList.push(data.attachment)
},
delPerformanceList(id) {
this.applyForm.performanceIndexList = this.applyForm.performanceIndexList.filter(item => item.id !== id)
},
}
文件分片
分片上传
<template>
<!-- 上传器 -->
<uploader
ref="uploader"
:options="options"
:autoStart=false
:file-status-text="fileStatusText"
@file-added="onFileAdded"
@file-success="onFileSuccess"
@file-error="onFileError"
class="uploader-ui">
<uploader-unsupport></uploader-unsupport>
<uploader-drop>
<div>
<uploader-btn id="global-uploader-btn" :attrs="attrs" ref="uploadBtn">选择文件<i
class="el-icon-upload el-icon--right"></i></uploader-btn>
</div>
</uploader-drop>
<uploader-list></uploader-list>
</uploader>
</template>
<script>
import {ACCEPT_CONFIG} from "@/api/dkyun/config.js"
import SparkMD5 from 'spark-md5';
import {mergeFile} from "@/api/dkyun/dkyun.js"
import {getToken} from '@/utils/auth'
import bus from "../bus.js"
export default {
data() {
return {
url: "",
superId: "",
options: {
target: 'http://10.3.74.84:9773/' + "wds/uploader/chunk",
chunkSize: '2048000',
fileParameterName: 'upfile',
maxChunkRetries: 3,
testChunks: true,
headers: {
JWTHeaderName: getToken() ? getToken() : ''
},
},
attrs: {
accept: ACCEPT_CONFIG.getAll()
},
fileStatusText: {
success: '上传成功',
error: '上传失败',
uploading: '上传中',
paused: '暂停',
waiting: '等待上传'
},
}
},
methods: {
onFileAdded(file) {
this.computeMD5(file);
console.log("添加文件完成")
console.log(this.superId, "asdfgh");
},
onFileSuccess(rootFile, file, response, chunk) {
console.log("onFileSuccess")
file.refProjectId = "123456789";
file.superId = this.$store.state.dkyun.superid;
console.log("file.superIdfile.superId", file.superId)
console.log("file111", JSON.stringify(file))
console.log("fize.size", file.size)
mergeFile(file).then(responseData => {
if (responseData.data.code === 415) {
console.log("合并操作未成功,结果码:" + responseData.data.code);
}
}).catch(function (error) {
console.log("合并后捕获的未知异常:" + error);
});
},
onFileError(rootFile, file, response, chunk) {
console.log('上传完成后异常信息:' + response);
},
computeMD5(file) {
file.pause();
let fileSizeLimit = 3 * 1024 * 1024 * 1024;
console.log("文件大小:" + file.size);
console.log("限制大小:" + fileSizeLimit);
if (file.size > fileSizeLimit) {
this.$message({
showClose: true,
type: 'error',
message: '文件大小不能超过3G'
});
location.reload()
return;
}
let fileReader = new FileReader();
let time = new Date().getTime();
let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
let currentChunk = 0;
const chunkSize = 10 * 1024 * 1000;
let chunks = Math.ceil(file.size / chunkSize);
let spark = new SparkMD5.ArrayBuffer();
let chunkNumberMD5 = 1;
loadNext();
fileReader.onload = (e => {
spark.append(e.target.result);
if (currentChunk < chunkNumberMD5) {
loadNext();
} else {
let md5 = spark.end();
file.uniqueIdentifier = md5;
file.resume();
console.log(`MD5计算完毕:${file.name} \nMD5:${md5} \n分片:${chunks} 大小:${file.size} 用时:${new Date().getTime() - time} ms`);
}
});
fileReader.onerror = function () {
this.error(`文件${file.name}读取出错,请检查该文件`)
file.cancel();
};
function loadNext() {
let start = currentChunk * chunkSize;
let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
currentChunk++;
console.log("计算第" + currentChunk + "块");
}
},
close() {
this.uploader.cancel();
},
error(msg) {
this.$notify({
title: '错误',
message: msg,
type: 'error',
duration: 2000
})
}
},
created() {
console.log("create1111")
this.url = localStorage.getItem('baseURL')
console.log(this.url, "urlrrrrrrrr")
},
watch: {
"$store.state.dkyun.superid"(current) {
this.superId = current;
}
}
}
</script>
<style>
.uploader-ui {
padding: 15px;
margin: 40px auto 0;
font-size: 12px;
font-family: Microsoft YaHei;
box-shadow: 0 0 10px rgba(0, 0, 0, .4);
}
.uploader-ui .uploader-btn {
margin-right: 4px;
font-size: 12px;
border-radius: 3px;
color: #FFF;
background-color: #409EFF;
border-color: #409EFF;
display: inline-block;
line-height: 1;
white-space: nowrap;
}
.uploader-ui .uploader-list {
max-height: 440px;
overflow: auto;
overflow-x: hidden;
overflow-y: auto;
}
</style>
分片下载
<template>
<el-dialog title="文件下载" :visible.sync="downloadVisible" width="60%">
<div class="warning"> 文件正在下载中,请勿操作电脑!</div>
<el-progress :text-inside="true" :stroke-width="16" :percentage="percentage" status="success"></el-progress>
<span slot="footer">
<el-button type="danger" @click="cancleDownload">取消下载</el-button>
</span>
</el-dialog>
</template>
methods: {
async downfiles(row) {
this.downloadVisible = true
this.downloading = true
this.percentage = 0
console.log(row, "下载文件下载文件");
let fileId = row.fileId.toString()
const request1 = {
fileId: fileId
}
const res = await getDownloadChunks(request1)
this.totalNum = res.data.number
console.log('块数', this.totalNum)
if (this.downloading == true) {
let result = []
console.log('result', result)
for (let i = 0; i < this.totalNum; i++) {
if (this.downloading == true) {
let request = {
newFileName: row.fileName,
fileId: fileId,
shareId: row.shareId,
index: i + 1
};
console.log('this.downloading)【【【【【【【【【【【', this.downloading)
console.log("i2223=", i)
const percentageNow = parseInt(i / this.totalNum * 100)
console.log(percentageNow)
this.percentage = percentageNow
this.downloading = true
const Response = await downloadfile(request)
console.log("Response", Response.data);
const blob = Response.data
result.push(blob)
if (i == this.totalNum - 1) {
this.percentage = 100
this.downloading = false
const data = new Blob(result, {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})
const a = document.createElement('a')
const href = window.URL.createObjectURL(data)
a.href = href
a.download = row.fileName
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(href)
this.downloadVisible = false
this.$message({
type: "success",
message: "下载成功",
});
}
}
}
}
},
cancleDownload() {
this.downloadVisible = false
this.downloading = false
this.percentage = 0
this.$message('已取消下载')
},
}