Vue Excel下载上传
jimyking 人气:0相信大家在项目中经常会遇到一些上传下载文件的相关功能,本文就Excel的相关功能进行简述:
咱直接看代码:
<div class="import-main-content"> <div class="import-main-button" @click="checkFile"> <div class="import-center" style="cursor: hand"> <div>+</div> <div>上传Excel文件</div> </div> </div> <div style="margin: 5px auto; width: 350px"> <div class="image-multiple-area" v-if="fileName"> <span>{{ fileName }}</span> <img @click="removes" style="position: absolute; top: -1px; right: -1px" src="@/assets/icons/tag-remove-icon.png" class="remove-excel" alt="" /> </div> <div v-else>尚未选择文件!</div> <div class="import-notice">注意:</div> <div class="import-notice"> 1. 请按照Excel表格模板内字段格式进行上传 </div> <div class="import-notice">2. 导入表格数量控制在10000条以内</div> <div class="import-notice"> 3. Excel表格模板点击下载:<span style="color: #277cf0" @click="downLoadModel" >Excel表格模板</span > </div> </div> <input type="file" id="fileinput" style="display: none" @change="checkFileSure" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" /> </div>
data () { return { fileName: "", //Excel文件 fileDir: "", //Excel文件路径 } }, checkFile() { document.querySelector("#fileinput").click(); }, checkFileSure() { let fileObj = document.querySelector("#fileinput").files[0]; let file = document.querySelector("#fileinput"); if (fileObj) { this.fileName = fileObj.name; // 文件类型 let fileType = fileObj.type; let fileSize = fileObj.size; // 文件大小 if ( !( fileType === "application/vnd.ms-excel" || fileType === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) ) { this.msgError("上传文件仅支持 Excel 格式!"); file.value = ""; return false; } else if (fileSize / 1024 / 1024 > 50) { this.msgError("文件大小超过50M!"); file.value = ""; return false; } this.importDone(); } else { this.$message.error("请选择导入的excel文档!"); return false; } }, //下载Excel模版 downLoadModel() { //getImportTempFile4Prize 为下载excel 模板接口 getImportTempFile4Prize().then((res) => { window.location.href = `${this.$store.state.weShop.IMGHEAD}${res.URI}`; }); }, importDone() { if (this.fileName == null || this.fileName === "") { this.$message.error("请选择导入的excel文档!"); return; } let fileObj = document.querySelector("#fileinput").files[0]; console.log(fileObj.name); let file = document.querySelector("#fileinput"); console.log(file); if (fileObj?.name) { let formData = new FormData(); formData.append("file", fileObj); formData.append("upload_type", "02"); let fileType = fileObj.type.split("/")[1]; // uploadExcel 为后台上传Excel 接口 uploadExcel(formData, fileType) .then((res) => { file.value = ""; this.fileDir = res.PATH; this.form.PRIZE_NUM = res.NUM; }) .catch(() => { file.value = ""; }) .then((res) => {}); document.querySelector("#fileinput").value = ""; } else { this.$message.error("请选择导入的excel文档!"); document.querySelector("#fileinput").value = ""; this.fileName = ""; return false; } },
以上逻辑在后台接口,前端主要做的是一些简要的操作,需要上传Excel的话需要先上传到服务器才行。
加载全部内容