vue上传文件

elementplus弹框版本可忽略
<el-dialog v-model="showForm" title="数据导入" width="30%" :before-close="handleClose">
			<!-- <span>This is a message</span> -->
			<el-upload class="upload-file" action="#" :before-upload="beforeUpload" :http-request="uploadFile"
				accept="xls,xlsx" style="text-align: center;">
				<el-button type="primary"  size="small"
					style="background: #31c75f;color: white;height: 40px;">点击上传
				</el-button>
			</el-upload>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showForm = false" style="margin-right: 10px;">取消</el-button>
					<!-- <el-button type="primary" @click="uploadFile">
		          确定
		        </el-button> -->
				</span>
			</template>
		</el-dialog>

以下即可实现所有通用

<el-upload class="upload-file" action="#" :before-upload="beforeUpload" :http-request="uploadFile"
				accept="xls,xlsx">
				<el-button  v-has="$TF.btnList('导入')"  type="primary" icon="el-icon-document-add" size="small"
					style=" margin-left: 20px;color: #000;background-color: #3031330d;border-color: #3031330d;">项目导入
				</el-button>
</el-upload>


js部分:

import {
getBase64
} from '@/assets/js/common.js'
methods: {
// 导入
			beforeUpload(file) {
				let fileName = file.name;
				let fileType = fileName.substring(fileName.lastIndexOf('.'));
				if (fileType != '.xls' && fileType != '.xlsx') {
					this.$message.error('请上传Excel文件!');
					return false;
				}
			},
			uploadFile(data) {
				getBase64(data.file).then(resBase64 => {
					// console.log(resBase64.split(',')[1])转为base64格式再进行请求接口
					GetExcelToDB5(resBase64.split(',')[1]).then(res => {
						if (res.data.state == 0) {
							// this.$alert('导入成功', '确认信息', {
							// 	confirmButtonText: '确定',
							// 	dangerouslyUseHTMLString: true
							// });
							this.$message.success('成功');
							this.onSearch();
							//this.$message.ale(res.data.message);
						} else {
							// this.$message.error(res.data.message);
							this.$alert('<strong>' + res.data.message + '</strong>', '错误提示', {
								dangerouslyUseHTMLString: true,
							});
						}
					})
				});
			},
}

common.js:文件


/* 时间格式化--世界时转为北京时间 */
import Vue from 'vue'
// import moment from 'moment';
// 将定义好的i18文件导入到js文件中 import i18n from '../i18n/i18n.js'’你可以查看 i18n对象的原型上有个t 方法 直接调用就可以 i18.t(‘xxxx’)
// import i18n from '../i18n/i18n.js'


function getBase64(file) {
	return new Promise((resolve, reject) => {
		let reader = new FileReader();
		let fileResult = "";
		reader.readAsDataURL(file);
		//开始转
		reader.onload = function() {
			fileResult = reader.result;
		};
		//转 失败
		reader.onerror = function(error) {
			reject(error);
		};
		//转 结束  咱就 resolve 出去
		reader.onloadend = function() {
			resolve(fileResult);
		};
	});
}
export {

getBase64,

}

posted @ 2022-11-04 16:57  FancyAnnaYL  阅读(63)  评论(0编辑  收藏  举报