本期为Vue项目常见的文档导入调接口需求, 提供给不太懂的朋友, 本人萌新一枚, 写的不好各位大佬还请谅解, 感谢!!!
本文分为两阶段 —— 1: 代码块阶段 2: 图文阶段 (框架为 ElementUI)
代码块阶段
结构样式👇
以下upload-file, 是我自己封装的ElementUI的<el-upload></el-upload>
<div style="float: right; margin-left: 10px;"> <upload-file text="模板导入" :data="otherData" :url="uploadURL" @success="uploadSuccess" > </upload-file> </div>
为了方便学习, 下面代码块为封装结构(--建议还是写el-upload吧--)👇
<template> <!--使用说明: <upload-file text="导入" :url="uploadUrl" @success="uploadCallback"></upload-file> 属性 text:为上传按钮显示的文字,必填 url:为上传的url地址,必填 btnQx:权限按钮控制,若不需控制按钮权限,不传即可,有权限按钮控制,值为是否有权限的boolear值 accept:上传文件类型,默认为excel disabled:禁用 默认false 事件: success:上传成功的回调函数,返回后台返回的值 --> <el-upload class="upload-demo" v-if="btnQx" :action="url" :data="data" :drag="drag" :headers="importHeaders" :on-success="uploadSuccess" :on-progress="uploadLoading" :before-upload="beforeAvatarUpload" :on-error="uploadError" :show-file-list="false" :accept="accept" style="display: inline-block;" :disabled="disabled" > <slot> <el-button :type="btnType" size="mini" :disabled="disabled"> <i class="iconfont icon-daoru1"></i> {{ text }} </el-button> </slot> </el-upload> </template> <script> import { getToken } from '@/util/auth' import website from '@/config/website' import { Base64 } from 'js-base64' export default { name: 'UploadFile', props: { btnType: { type: String, default: 'primary', }, text: { type: String, default: '导入', }, drag: { type: Boolean, default: false }, btnQx: { type: Boolean, default: () => true, }, data: { type: Object, default: () => { return {} }, }, url: { type: String, required: true, }, accept: { type: String, default: '.xls,.xlsx', }, disabled: { type: Boolean, default: () => false, } }, data() { return { importHeaders: { Authorization: `Basic ${Base64.encode( `${website.clientId}:${website.clientSecret}` )}`, 'MagicCube-Auth': 'bearer ' + getToken(), }, loading: false, imgQuality: 0.3, } }, methods: { uploadSuccess(res) { // this.loading.close(); this.$emit('success', res) }, uploadLoading() { this.loading = this.$loading({ lock: true, text: '正在努力上传,请稍后...', spinner: 'el-icon-loading', }) }, uploadError(err) { let obj = JSON.parse(err.toString().replace(/(Error: )/, '')) // this.loading.close(); this.$message.error(obj.msg) }, dataURItoBlob(dataURI, type) { var binary = atob(dataURI.split(',')[1]) var array = [] for (var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)) } return new Blob([new Uint8Array(array)], { type: type }) }, beforeAvatarUpload(file) { if (file.name.search('[.]+(jpg|jpeg|swf|gif|png|JPG|JPEG|SWF|GIF|PNG)$') != -1) { const _this = this return new Promise((resolve) => { const reader = new FileReader() const image = new Image() image.onload = () => {//(imageEvent) => { const canvas = document.createElement('canvas') const context = canvas.getContext('2d') const width = image.width * _this.imgQuality const height = image.height * _this.imgQuality canvas.width = width canvas.height = height context.clearRect(0, 0, width, height) context.drawImage(image, 0, 0, width, height) const dataUrl = canvas.toDataURL(file.type) const blobData = _this.dataURItoBlob(dataUrl, file.type) resolve(blobData) } reader.onload = (e) => { image.src = e.target.result } reader.readAsDataURL(file) console.log(file.size) }) }else if (file.name.search('[.]+(pdf|PDF|doc|DOC|docx|DOCX|XLSX|xlsx|xls|XLS)$') != -1){ console.log(file) if (file.size > 5242880){ this.$message.warning('上传文件不能大于5M!'); return false } } }, }, } </script> <style lang="scss" scoped> .fileImage { margin-top: 10px; } </style>
数据结构👇
export default { components: { UploadFile }, // 引入的封装结构 name: "upload", // 完全自定义name, 不会有人不知道吧, 不会吧不会吧(doge) data () { return { uploadURL: importCompanyExcel, // 接口的url地址 otherData: { CompanyDetailId: this.$store.getters.customer.id // 接口需要的参数 } } } }
// 此代码块为存放接口的 JS 文件 // 文档导入操作 export const importCompanyExcel = "请求的接口URL";
上传成功钩子函数👇
uploadSuccess (res) { if (res.code == 200) { // 接口返回200(成功) this.getList(this.pagination); // 调用其他接口 this.$alert(res.msg, '提示', { confirmButtonText: '确定', callback: () => { this.page.currentPage = 1 this.onLoad(this.page, this.query) // 调用其他接口 }, }) } else { this.$message.error(res.msg) // 失败 } },
图文阶段(简单暴力上图)👇
结构样式
数据结构
引入接口
本文比较简单粗暴, 不会讲解太详细, 希望各位见谅, 本人还是萌新🤗
感谢各位佬