123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <template>
- <div>
- <el-upload
- :action="oss_url"
- :data="dataObj"
- :multiple="false"
- :show-file-list="showFileList"
- :file-list="fileList"
- :before-upload="beforeUpload"
- :on-remove="handleRemove"
- :on-success="handleUploadSuccess"
- >
- <el-button size="small" type="primary">{{fileList.length == 0 ? '点击上传':'重新上传'}}</el-button>
- </el-upload>
- </div>
- </template>
- <script>
- import request from '@/utils/request';
- import { getOssConfig } from '@/api/common'
- export default {
- name: 'importUpload',
- props: {
- fileList: Array
- },
- data() {
- return {
- oss_url: '',
- dataObj: {},
- };
- },
- created() {
- getOssConfig().then(res => {
- this.oss_url = res.data.host
- })
- },
- computed: {
- showFileList: {
- get: function() {
- if (this.fileList.length > 0 && this.fileList[0].url) {
- return true;
- } else {
- return false;
- }
- },
- set: function(newValue) {}
- }
- },
- methods: {
- // 获取oss配置
- async getOssConfig(fileName) {
- const result = await new Promise((resolve, reject) => {
- getOssConfig()
- .then(res => {
- const fileKey = this.createName(fileName)
- res.data.name = fileName
- res.data.key = res.data.dir + fileKey
- resolve(res.data)
- })
- .catch(res => {
- resolve({})
- })
- })
- return result
- },
- getUUID() {
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
- return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
- });
- },
- createName(name) {
- const date = Date.now();
- const uuid = this.getUUID();
- const fileSuffix = name.substring(name.lastIndexOf(".") + 1);
- return `${date}${uuid}.${fileSuffix}`;
- },
- handleRemove(file, fileList) {
- this.fileList = [{ name: '', url: '' }];
- },
- async beforeUpload(file) {
- const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
- const whiteList = ['xls', 'xlsx', 'xlsm'];
- if (whiteList.indexOf(fileSuffix) === -1) {
- return this.$errorMsg('只支持上传excel表格文件!');
- }
- const fileName = this.createName(file.name);
- const loading = this.$loading({
- lock: true,
- text: 'Loading',
- spinner: 'el-icon-loading',
- background: 'rgba(0, 0, 0, 0.7)'
- });
- this.dataObj = await this.getOssConfig(fileName);
- },
- handleUploadSuccess(res, file, fileList) {
- const loading = this.$loading({
- lock: true,
- text: 'Loading',
- spinner: 'el-icon-loading',
- background: 'rgba(0, 0, 0, 0.7)'
- });
- this.fileList.pop();
- this.fileList.push({
- name: file.name,
- url: this.dataObj.key
- });
- this.showFileList = true;
- loading.close();
- }
- }
- };
- </script>
|