vue 之 ele上传文件与下载文件 ele+手写 (不提倡)
vue 之 ele上传文件
- 一点击选取文件的时候,直接对接后端接口,上传文件,获取返回的数据对象
- 可以删除已上传的文件,也需要对接后端接口进行删除
<template>
<div class="upload_file clear_fix">
<div class="upload_file_title">{{ title }}</div>
<div class="upload_file_btn">
<el-form :model="uploadForm" οnsubmit="return false">
<el-form-item label="">
<el-upload
ref="uploadForm"
action=""
:file-list="fileList"
:on-change="handleFileChange"
:on-remove="removeFile"
:auto-upload="false"
multiple
accept=".doc,.docx,.ppt,.pptx,.xls,.xlsx,.pot,.pps,.vsd,.rtf,.wps,.et,.dps,.pdf,.txt,.7z,.rar,.zip"
>
<el-button size="small" type="primary" slot="trigger"
>选取文件</el-button
>
</el-upload>
</el-form-item>
</el-form>
<div class="upload_file_tip">
<div>支持格式:</div>
<div>jpg、png、</div>
<div>docx、xlsx等</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import { baseUrl } from "@/utils/request.js";
import { removeFileGet } from "@/api/creditManagement/singleAdd/singleAdd.js";
export default {
name: "UploadFile",
components: {},
props: {
clearFileFlag: {
type: Boolean,
default: false,
},
},
data() {
return {
title: "上传文件:",
fileList: [],
uploadForm: {},
file: {}, // 上传文件
uploadAllFile: [], // 上传的文件的所有数据
// clearFile: false, // 清除 上传的文件的flag
};
},
watch: {
uploadAllFile(val) {
this.uploadAllFile = val;
this.$emit("uploadAllFile", this.uploadAllFile);
},
clearFileFlag(val) {
// this.clearFile = val;
// console.log("上传文件的flag", val);
if (val) {
this.file = {};
this.uploadAllFile = [];
let dom = document.querySelector(".el-upload-list");
let donChildObj = dom.childNodes;
for (var i = donChildObj.length - 1; i >= 0; i--) {
// 一定要倒序删除dom子节点
dom.removeChild(donChildObj[i]);
}
// console.log("dom2", dom);
this.$store.commit("clearFileFlag", false);
}
},
},
methods: {
//上传文件,获取文件流
handleFileChange(file, fileList) {
this.$store.commit("clearFileFlag", false);
this.file = file.raw;
// 创建表单对象 用于数据的格式 + 用于添加流文件!
let formData = new FormData();
formData.append("files", this.file);
axios
.post(baseUrl + "/eap/uploadFile", formData, {
headers: {
"Content-Type": "multipart/form-data",
Token: JSON.parse(sessionStorage.getItem("token")),
},
})
.then(({ data }) => {
// console.log("上传文件data", data.dat);
if (data.code == 0) {
file.busiid = data.dat[0].busiid;
this.uploadAllFile.push(data.dat[0]);
this.$message({ type: "success", message: "上传文件成功" });
} else {
let dom = document.querySelector(".el-upload-list")
let donChildObj = dom.childNodes;
dom.removeChild(donChildObj[donChildObj.length - 1]);
this.uploadAllFile.pop();
this.$message({ type: "error", message: "上传文件失败" });
}
});
},
// 删除文件
removeFile(file) {
// console.log("移除文件", file);
removeFileGet(file.busiid).then(({ data }) => {
if (data.code == 0) {
this.$message({ type: "success", message: "删除文件成功" });
} else {
this.$message({ type: "error", message: data.dat });
}
});
this.uploadAllFile = this.uploadAllFile.filter((item) => {
return item.busiid != file.busiid;
});
},
},
};
</script>
<style lang="scss" scoped>
.upload_file {
// position: relative;
// top: -15px;
background: #fff;
.upload_file_title {
float: left;
text-align: right;
width: 110px;
height: 40px;
line-height: 40px;
}
.upload_file_btn {
position: relative;
float: left;
}
.upload_file_tip {
position: absolute;
top: 35px;
left: 0px;
width: 80px;
height: 49px;
div {
font-size: 12px;
font-family: SourceHanSansCN-Regular, SourceHanSansCN;
font-weight: 400;
color: #b9bcc5;
line-height: 14px;
}
}
}
::v-deep .el-button--small {
padding: 6px 16px !important;
}
::v-deep .el-upload-list {
position: relative;
left: 100px;
top: -34px;
width: 640px;
background: #000;
clear: both;
li {
float: left;
width: 33% !important;
}
.el-upload-list__item {
margin-top: 10px !important;
}
}
</style>
vue之下载文件
downloadBtn(row) {
if (row.contractno) {
getDownloadFile(row.contractno).then(({ data }) => {
if (data.code == 0 && data.dat && data.dat.length > 0) {
axios
.post(baseUrl + "/eap/downloadFile", data.dat, {
headers: {
"Content-Type": "application/json;charset=UTF-8",
Token: JSON.parse(sessionStorage.getItem("token")),
},
responseType: "blob",
})
.then((res) => {
let link = document.createElement("a");
let blob = new Blob([res.data], {
type: "application/zip",
});
link.style.display = "none";
link.href = URL.createObjectURL(blob);
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, "附件1.zip");
} else {
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = "附件2.zip";
link.click();
window.URL.revokeObjectURL(link.href);
}
});
}
});
} else {
this.$message({
message: "温馨提示:合同编号不能为空",
type: "warning",
});
}
},
上传组件的回显 + 添加删除 与下载事件
<template>
<div class="upload_file clear_fix">
<!-- lowApplyStatus {{ lowApplyStatus }} isDisable {{ isDisable }} -->
<!-- uploadFile -- {{ uploadFile }} -->
<!-- uploadAllFile -- {{ uploadAllFile }} -->
<div class="upload_file_title">{{ title }}</div>
<div class="upload_file_btn">
<el-form :model="uploadForm" onsubmit="return false">
<el-form-item label="">
<el-upload
ref="uploadForm"
action=""
:file-list="fileList"
:on-change="handleFileChange"
:on-remove="removeFile"
:auto-upload="false"
multiple
:disabled="isDisable"
accept=".doc,.docx,.ppt,.pptx,.xls,.xlsx,.pot,.pps,.vsd,.rtf,.wps,.et,.dps,.pdf,.txt,.7z,.rar,.zip"
>
<el-button
size="small"
type="primary"
slot="trigger"
:disabled="isDisable"
>选取文件</el-button
>
</el-upload>
</el-form-item>
</el-form>
<div class="upload_file_tip">
<div>支持格式:</div>
<div>jpg、png、</div>
<div>docx、xlsx等</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import { baseUrl } from "@/utils/request.js";
import { postSign } from "@/utils/sign.js";
import {
removeFileGet,
downloadFileGet,
} from "@/api/creditManagement/singleAdd/singleAdd.js";
import { deepCopy } from "@/utils/createTool.js";
import requestDown from "@/utils/requestDown";
import { getDownloadFile } from "@/api/creditManagement/businessQuery/ExternalCreditDetailsQuery";
export default {
name: "UploadFileEdit",
components: {},
props: {
uploadFile: {
type: Array,
default() {
return [];
},
},
lowApplyStatus: {
type: String,
default: "",
},
},
data() {
return {
title: "上传文件:",
fileList: [],
uploadForm: {},
file: {}, // 上传文件
uploadAllFile: [],
isDisable: false, // 是否禁用
// uploadAllFile: this.uploadFile, // 上传的文件的所有数据
};
},
watch: {
uploadAllFile: {
handler(newV) {
// console.log("最新的文件val", newV);
// 给当前 li 添加下载功能
let allLiDom = document.querySelectorAll(".el-upload-list li");
// console.log("allLiDom", allLiDom);
let _this = this;
if (allLiDom && allLiDom.length > 0) {
for (let i = 0; i < allLiDom.length; i++) {
allLiDom[i].onclick = function () {
// console.log("li的点击事件 监听的", i, newV[i].busiid);
_this.$message({ message: "温馨提示:文件下载之中", type: "success" });
if (newV && newV.length > 0) {
let obj = {
busiid: newV[i].busiid,
filename: newV[i].filename,
};
requestDown({
url: "/eap/downloadSingle",
method: "get",
responseType: "blob",
params: {
...obj,
},
}).then((res) => {
let link = document.createElement("a");
//ArrayBuffer 转为 Blob
let blob = new Blob([res]);
link.style.display = "none";
link.href = URL.createObjectURL(blob);
if ("msSaveOrOpenBlob" in navigator) {
window.navigator.msSaveOrOpenBlob(blob, obj.filename);
} else {
link.setAttribute("download", obj.filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
}
};
}
}
this.uploadAllFile = newV;
this.$emit("uploadAllFile", this.uploadAllFile);
},
deep: true,
},
},
created() {
this.uploadAllFile = deepCopy(this.uploadAllFile, this.uploadFile);
},
mounted() {
this.init();
},
methods: {
init() {
if (this.lowApplyStatus === "0" || val === "1") {
this.isDisable = false;
} else {
this.isDisable = true;
}
if (this.uploadFile && this.uploadFile.length > 0) {
let dom = document.querySelector(".el-upload-list");
// console.log('初始化的dom', dom);
let html = this.uploadFile.map((item) => {
return `
<li tabindex="0" class="el-upload-list__item is-ready" data-busiid="${item.busiid}" data-filename="${item.filename}">
<a class="el-upload-list__item-name"><i class="el-icon-document"></i>${item.filename}</a>
<label class="el-upload-list__item-status-label"><i class="el-icon-upload-success el-icon-circle-check"></i></label>
<i class="el-icon-close el-icon-close-extar" data-id="${item.id}" ></i>
<i class="el-icon-close-tip">按 delete 键可删除</i>
</li>
`;
});
dom.innerHTML = html;
let _this = this;
// 给 X 添加删除事件
let allDom = document.querySelectorAll(".el-icon-close-extar");
if (allDom && allDom.length > 0) {
for (let i = 0; i < allDom.length; i++) {
allDom[i].onclick = function (event) {
event.stopPropagation();
if (!_this.isDisable) {// 不是禁用状态的时候 有删除
// console.log('i', i,"allDom",allDom[i].dataset.id);
if (_this.uploadAllFile && _this.uploadAllFile.length > 0) {
_this.uploadAllFile = _this.uploadAllFile.filter((item) => {
return item.id != allDom[i].dataset.id;
});
// console.log("删除后的", _this.uploadAllFile);
dom.removeChild(allDom[i].parentNode);
_this.$message({ message: "删除文件成功", type: "success" });
}
} else {
_this.$message({
message: "温馨提示:禁用状态,不可删除",
type: "warning",
});
}
};
}
}
// 给当前 li 添加下载功能
let allLiDom = document.querySelectorAll(".el-upload-list li");
if (allLiDom && allLiDom.length > 0) {
for (let i = 0; i < allLiDom.length; i++) {
allLiDom[i].onclick = function () {
// console.log("点击事件",allLiDom[i].dataset.busiid);
_this.$message({ message: "温馨提示:文件下载之中", type: "success" });
let obj = {
busiid: allLiDom[i].dataset.busiid,
filename: allLiDom[i].dataset.filename,
};
requestDown({
url: "/eap/downloadSingle",
method: "get",
responseType: "blob",
params: {
...obj,
},
}).then((res) => {
let link = document.createElement("a");
let blob = new Blob([res]);
link.style.display = "none";
link.href = URL.createObjectURL(blob);
if ("msSaveOrOpenBlob" in navigator) {
window.navigator.msSaveOrOpenBlob(blob, obj.filename);
} else {
link.setAttribute("download", obj.filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
};
}
}
}
},
//上传文件,获取文件流
handleFileChange(file, fileList) {
this.file = file.raw;
// 创建表单对象 用于数据的格式 + 用于添加流文件!
let formData = new FormData();
formData.append("files", this.file);
let obj = {
...this.file,
_t: Date.parse(new Date()) / 1000,
};
let sign = postSign(obj);
formData.append("sign", sign);
formData.append("_t", obj._t);
formData.append("uid", this.file.uid);
axios
.post(baseUrl + "/eap/uploadFile", formData, {
headers: {
From: "cmas-ui",
"Content-Type": "multipart/form-data",
Token: JSON.parse(sessionStorage.getItem("token")),
},
})
.then(({ data }) => {
// console.log("上传文件data", data.dat);
if (data.code == 0) {
file.busiid = data.dat[0].busiid;
this.uploadAllFile.push(data.dat[0]);
this.$message({ type: "success", message: "上传文件成功" });
} else {
let dom = document.querySelector(".el-upload-list");
let donChildObj = dom.childNodes;
dom.removeChild(donChildObj[donChildObj.length - 1]);
this.uploadAllFile.pop();
this.$message({ type: "error", message: "上传文件失败" });
}
});
},
// 删除文件
removeFile(file) {
// console.log("移除文件", file);
if (file.busiid) {
removeFileGet(file.busiid).then(({ data }) => {
if (data.code == 0) {
this.$message({ type: "success", message: "删除文件成功" });
} else {
this.$message({ type: "error", message: data.dat });
}
});
this.uploadAllFile = this.uploadAllFile.filter((item) => {
return item.busiid != file.busiid;
});
// this.$message({ type: "success", message: "删除文件成功" });
}
},
},
};
</script>
<style lang="scss" scoped>
.upload_file {
// position: relative;
// top: -15px;
padding-top: 5px;
background: #fff;
.upload_file_title {
float: left;
text-align: right;
width: 110px;
height: 40px;
line-height: 40px;
}
.upload_file_btn {
position: relative;
float: left;
}
.upload_file_tip {
position: absolute;
top: 35px;
left: 0px;
width: 80px;
height: 49px;
div {
font-size: 12px;
font-family: SourceHanSansCN-Regular, SourceHanSansCN;
font-weight: 400;
color: #b9bcc5;
line-height: 14px;
}
}
}
::v-deep .el-button--small {
padding: 6px 16px !important;
}
::v-deep .el-upload-list {
position: relative;
left: 100px;
top: -34px;
width: 640px;
// background: #000;
clear: both;
li {
float: left;
width: 33% !important;
}
.el-upload-list__item {
margin-top: 10px !important;
}
}
.disableBtn {
cursor: not-allowed;
}
</style>
vue 之 ele上传文件与下载文件 方式2
<template>
<div class="upload_file clear_fix">
<div class="upload_file_title">{{ title }}</div>
<div class="upload_file_btn">
<el-form :model="uploadForm" onsubmit="return false">
<el-form-item label="">
<el-upload
action=""
:file-list="fileList"
:before-upload="beforeUpload"
:http-request="fnUploadRequest"
:on-remove="removeFile"
:on-preview="previewFile"
accept=".doc,.docx,.ppt,.pptx,.xls,.xlsx,.pot,.pps,.vsd,.rtf,.wps,.et,.dps,.pdf,.txt,.7z,.rar,.zip"
multiple
ref="uploadForm"
>
<el-button
size="small"
type="primary"
slot="trigger"
:disabled="isDisable"
>选取文件</el-button
>
</el-upload>
</el-form-item>
</el-form>
<div class="upload_file_tip">
<div>支持格式:</div>
<div>jpg、png、</div>
<div>docx、xlsx等</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import { baseUrl } from "@/utils/request.js";
import { postSign } from "@/utils/sign.js";
import {
removeFileGet,
} from "@/api/creditManagement/singleAdd/singleAdd.js";
import { deepCopy } from "@/utils/createTool.js";
import requestDown from "@/utils/requestDown";
export default {
name: "UploadFileEdit",
components: {},
props: {
uploadFile: {
type: Array,
default() {
return [];
},
},
lowApplyStatus: {
type: String,
default: "",
},
},
data() {
return {
title: "上传文件:",
fileList: [],
uploadForm: {},
file: {}, // 上传文件
uploadAllFile: [],
isDisable: false, // 是否禁用
};
},
watch: {
uploadAllFile: {
handler(newV) {
this.uploadAllFile = newV;
this.$emit("uploadAllFile", this.uploadAllFile);
},
deep: true,
},
},
created() {
this.uploadAllFile = deepCopy(this.uploadAllFile, this.uploadFile);
},
mounted() {
this.init();
},
methods: {
// 上传前的 文件名判断
beforeUpload(file){
let testReg = file.name.substring(0,file.name.lastIndexOf('.'));
console.log('testReg',testReg);
let reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
// console.log('res', reg.test(testReg));
let bool = false;
if ( reg.test(testReg) ) {
bool = true;
} else {
this.$message({ type: "error", message: "温馨提示:文件名仅支持:中文、英文、数字及下划线" });
bool = false;
}
// console.log('bool',bool);
return bool;
},
// 上传图片
fnUploadRequest(file,fileList) {
// console.log(file);
try {
this.file = file.file;
// 创建表单对象 用于数据的格式 + 用于添加流文件!
let formData = new FormData();
formData.append("files", this.file);
let obj = {
...this.file,
_t: Date.parse(new Date()) / 1000,
};
let sign = postSign(obj);
formData.append("sign", sign);
formData.append("_t", obj._t);
formData.append("uid", this.file.uid);
axios
.post(baseUrl + "/eap/uploadFile", formData, {
headers: {
From: "cmas-ui",
"Content-Type": "multipart/form-data",
Token: JSON.parse(sessionStorage.getItem("token")),
},
})
.then(({ data }) => {
console.log("上传文件data", data.dat);
if (data.code == 0) {
file.busiid = data.dat[0].busiid;
this.uploadAllFile.push(data.dat[0]);
this.$message({ type: "success", message: "上传文件成功" });
file.name = data.dat[0].filename;
} else {
this.$message({ type: "error", message: data.dat });
}
});
} catch {
this.$message({ type: "error", message: "事实是事实" });
}
},
// 上传文件的数据回显
init() {
if ( this.lowApplyStatus === "0" ) {
this.isDisable = false;
} else {
this.isDisable = true;
}
let uploadFile = [];
for (var index = 0; index < this.uploadFile.length; index++) {
uploadFile.push({
busiid: this.uploadFile[index].busiid,
name: this.uploadFile[index].filename,
});
}
console.log('回显uploadFile',uploadFile);
this.fileList = uploadFile;
},
// 删除文件
removeFile(file) {
if (file.busiid) {
removeFileGet(file.busiid).then(({ data }) => {
if (data.code == 0) {
this.$message({ type: "success", message: "删除文件成功" });
} else {
this.$message({ type: "error", message: data.dat });
}
});
this.uploadAllFile = this.uploadAllFile.filter((item) => {
return item.busiid != file.busiid;
});
}
},
// 已经上传成功的 文件 可添加下载功能
previewFile(file){
console.log('已经上传的 可以实现点击下载文件', file);
let obj = {
busiid: newV[i].busiid, // uid 需要使用
filename: newV[i].filename,
};
requestDown({
url: "/eap/downloadSingle",
method: "get",
responseType: "blob",
params: {
...obj,
},
}).then((res) => {
let link = document.createElement("a");
let blob = new Blob([res]);
link.style.display = "none";
link.href = URL.createObjectURL(blob);
if ("msSaveOrOpenBlob" in navigator) {
window.navigator.msSaveOrOpenBlob(blob, obj.filename);
} else {
link.setAttribute("download", obj.filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
}
},
};
</script>
<style lang="scss" scoped>
.upload_file {
padding-top: 5px;
background: #fff;
.upload_file_title {
float: left;
text-align: right;
width: 110px;
height: 40px;
line-height: 40px;
}
.upload_file_btn {
position: relative;
float: left;
}
.upload_file_tip {
position: absolute;
top: 35px;
left: 0px;
width: 80px;
height: 50px;
div {
font-size: 12px;
font-family: SourceHanSansCN-Regular, SourceHanSansCN;
font-weight: 400;
color: #b9bcc5;
line-height: 15px;
}
}
}
::v-deep .el-button--small {
padding: 6px 16px !important;
}
::v-deep .el-upload-list {
position: relative;
left: 100px;
top: -34px;
width: 640px;
// background: #000;
clear: both;
li {
float: left;
// width: 33% !important;
width: 50% !important;
}
.el-upload-list__item {
margin-top: 10px !important;
}
}
.disableBtn {
cursor: not-allowed;
}
</style>