<template>
<div class="upload-file pms-upload-file">
<el-upload class="upload-demo" name="fileName" :action="action" :headers="headers" :accept="fileType.join(',')"
:before-upload="handleBeforeUpload" :multiple="multiple" :on-change="handleChange" :on-progress="handleProgress"
:on-error="handleError" :on-success="handleSuccess" :on-remove="handleRemove" :data="data" :file-list="fileList"
ref="fileUpload">
<el-button slot="trigger" type="primary">上传</el-button>
<div slot="tip" class="el-upload__tip" style="color: #F56C6C">
支持{{ multiple ? "多" : "单" }}文件上传,支持<span style="color: #F56C6C">{{ fileType.join(", ") }}</span>格式
</div>
</el-upload>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: "FileUpload",
props: {
// 最多上传几个
limit: {
type: Number,
},
// 是否多选
multiple: {
type: Boolean,
default: false,
},
// 文件类型, 例如['png', 'jpg', 'jpeg']
Ftype: {
type: Number,
default: 0,
},
// 是否在选取文件后立即进行上传
autoUpload: {
type: Boolean,
default: true,
},
fileList: {
type: Array,
default: () => [],
},
// 是否在input事件回调中返回url字符串拼接
isReturnUrlStr: {
type: Boolean,
default: false,
},
action: {
type: String,
default:
window.location.origin + '/api' +
"/jeecg-supervise/supervise/minio/uploads", // 默认上传接口
},
// 上传文件的额外参数
data: {
type: Object,
default: () => {
return {};
},
},
},
data() {
return {
number: 0,
uploadList: this.fileList.slice(),
headers: {},
fileType: [],
};
},
destroyed() {
console.log("销毁了");
this.uploadList = [];
},
created() {
// 设置请求头
console.log('创建前');
this.setHeaders();
if (this.Ftype == 1) {
this.fileType = [".jpg", ".jpeg", ".png", ".bmp", ".webp"];
} else if (this.Ftype == 2) {
this.fileType = [".avi", ".mp4", ".mov", ".wmv"];
} else if (this.Ftype == 3) {
this.fileType = [".doc", ".docx", ".pdf", ".xls", ".xlsx", ".ofd"];
} else if (this.Ftype == 4) {
this.fileType = [
".jpg",
".jpeg",
".png",
".bmp",
".webp",
".doc",
".docx",
".pdf",
".xls",
".xlsx",
".ofd",
];
} else if (this.Ftype == 5) {
this.fileType = [
".jpg",
".jpeg",
".png",
".bmp",
".webp",
".doc",
".docx",
".pdf",
".xls",
".xlsx",
".ofd", ".avi", ".mp4", ".mov", ".wmv"
];
}
},
methods: {
// 设置请求头
setHeaders() {
// 上传请求头设置
this.headers = {
"X-Access-Token": sessionStorage.getItem("SUPERVISE_TOKEN"),
};
},
// 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
handleChange(file, fileList) {
// 当上传交互为手动触发再去上传时,通过该钩子获取file文件对象
},
// 文件删除调用
handleRemove(file, fileList) {
// 只有手动触发时再去删除
const index = this.uploadList.findIndex(
(fileItem) => fileItem.url === file.url
);
this.uploadList.splice(index, 1);
this.$emit("input", this.listToString(this.uploadList));
},
// 上传前校检格式和大小
handleBeforeUpload(file) {
console.log('上传前校检格式和大小');
// 校检文件类型
if (this.fileType) {
const fileName = file.name.split(".");
const fileExt = "." + fileName[fileName.length - 1];
const isTypeOk = this.fileType.indexOf(fileExt.toLowerCase()) >= 0;
if (!isTypeOk) {
this.$message2(
"warning",
`文件格式不正确, 请上传${this.fileType.join(",")}格式文件!`
);
return false;
}
}
// 校检文件大小
if (this.fileSize) {
const isLt = file.size / 1024 / 1024 < this.fileSize;
if (!isLt) {
this.$message2(
"warning",
`上传文件大小不能超过 ${this.fileSize} MB!`
);
return false;
}
}
// 设置请求头 sing 参数
// this.setHeaderSign(file);
this.number++;
return true;
},
handleProgress(event, file, fileList) {
console.log('文件上传进度条', event, file, fileList);
},
// 上传成功回调
handleSuccess(res, file, fileList) {
console.log('上传成功回调', res, file, fileList);
if (res.code == 200) {
if (this.limit == 1 && fileList.length > 1) {
fileList.splice(0, 1);
this.uploadList = fileList
} else {
this.uploadList = fileList
}
this.uploadedSuccessfully();
this.$message2("", res.message);
} else {
console.log(this.uploadList, this.$refs.fileUpload);
let uid = file.uid
let idx = this.$refs.fileUpload.uploadFiles.findIndex(item => item.uid === uid)
this.$refs.fileUpload.uploadFiles.splice(idx, 1)
}
},
// 上传失败回调
handleError(err, file, fileList) {
console.log(err, file, fileList);
},
// 上传结束处理
uploadedSuccessfully() {
console.log('上传结束处理', this.uploadList);
this.uploadList = this.uploadList.map((x) =>
x.response ? x.response.result[0] : x
);
this.$emit("input", this.listToString(this.uploadList));
},
// 获取文件名称
getFileName(name) {
console.log('获取文件名称');
if (name.lastIndexOf("/") > -1) {
return name.slice(name.lastIndexOf("/") + 1);
} else {
return name;
}
},
// 对象转成指定字符串分隔
listToString(list, separator) {
console.log('对象转成指定字符串分隔', this.isReturnUrlStr);
if (!this.isReturnUrlStr) {
return list;
}
let strs = "";
separator = separator || ",";
if (list.length > 1) {
list.forEach((item) => {
strs += item.url + separator;
});
console.log(strs);
return strs;
} else {
list.forEach((item) => {
strs += item.url;
});
console.log(strs);
return strs;
}
},
UploadFile(file) {
console.log(file);
let files = file.file
const fd = new FormData()
fd.append('fileName', files)
axios({
method: 'post',
url: window.location.origin + '/api' + "/jeecg-supervise/supervise/minio/uploads",
headers: { //如果需要权限下载的话,加在这里
'Content-Type': 'multipart/form-data',
// 'Content-Type': 'application/octet-stream',
'X-Access-Token': window.sessionStorage.getItem('SUPERVISE_TOKEN')
},
data: fd
}).then(res => {
console.log(res);
if (res.data.code == 200) {
let files = res.data.result
if (this.limit == 1 && files.length > 1) {
files.splice(0, 1);
this.uploadList.push(...files)
} else {
this.uploadList.push(...files)
}
this.uploadedSuccessfully();
this.$message2('', res.data.message)
} else {
let uid = files.uid
let idx = this.$refs.fileUpload.uploadFiles.findIndex(item => item.uid === uid)
this.$refs.fileUpload.uploadFiles.splice(idx, 1)
this.$message2('error', '上传失败')
}
})
},
// 清空fileList
resetFile() {
console.log(this.uploadList);
console.log("触发清空fileList");
this.uploadList = [];
},
},
};
</script>
<style scoped>
.hide>>>.el-upload {
display: none;
}
.el-button+.el-button {
margin-left: 0;
}
::v-deep .el-button {
/* width: 88px;
height: 40px;
background: #ebf2ff;
border-radius: 4px;
border: 1px solid #347dff;
color: #347DFF; */
padding: .625vw 1.0417vw !important;
}
/*small组件*/
.uploadImgSmall>>>.el-upload-list--picture-card .el-upload-list__item {
width: 4.1667vw;
height: 4.1667vw;
}
.uploadImgSmall>>>.el-upload--picture-card {
width: 4.1667vw;
height: 4.1667vw;
line-height: 4.5833vw;
}
>>>.el-upload__tip {
font-size: .625vw;
}
>>>.el-upload-list__item {
font-size: .7292vw;
}
>>>.el-upload-list__item .el-icon-close {
top: .2604vw;
right: .2604vw;
font-size: .8333vw;
}
</style>
基于vue2的element-ui文件上传二次封装