elementUi文件手动上传

1.安装element-ui,导入element

2.在vue文件中使用el-upload

<!-- accept 指定文件类型 -->
<!-- multiple 选择文件时是否支持多选 -->
<!-- file-lset 选择的文件列表 -->
<!-- before-upload 文件上传之前执行的操作  -->
<!-- http-request 自定义文件上传操作,手动上传需要调用upload组件的submit方法 -->
<el-upload
    ref="upload"
	accept=".xls,.xlsx" 
	action="#"
	:auto-upload="false"
	:multiple="false"
	:file-list="fileList"
	:before-upload="beforeUpload"
	:http-request="uploadHttpRequest"
	:headers="uploadHeaders"
	:on-remove="fileRemove"
	:on-change="fileChange"
>
	<el-button size="small" type="primary">选择文件</el-button>
	<div slot="tip" class="el-upload__tip">一次只能上传一个xls/xlsx文件,且不超过20M</div>
</el-upload>

3.在methods里面定义上传文件之前的操作和自定义文件上传的操作

// 文件上传之前的操作
beforeUpload(file) {
	// 文件类型
	const isType = file.type === 'application/vnd.ms-excel'
	const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
	const fileType = isType || isTypeComputer
	if (!fileType) {
		console.log('上传文件只能是xls/xlsx格式!')
	}

	// 文件大小限制为20M
	const fileLimit = file.size / 1024 / 1024 < 20
	if (!fileLimit) {
		console.log('上传文件大小不超过20M!')
	}
    // 返回判断条件,false停止上传
	return fileType && fileLimit
}

// 自定义上传方法,param是默认参数,可以取得file文件信息,具体信息如下图
uploadHttpRequest(param) {
    // FormData对象
	const formData = new FormData() .
    // 添加文件对象,key为需要发送的参数
	formData.append('excel', param.file) 
    // 上传地址
	const url = `${this.$baseUrl}${this.$attrs.curItem.importFn}` 
    // 获取token通过身份认证
	const token = util.cookies.get('token') 
	axios.post(url, formData, {
		headers: {
			'Content-Type': 'application/json',
			 Authorization: token ? ('Bearer ' + token) : ''
		}
	}).then(res => {
		var msg = ''
		if (res.data.error_code === 0) {
		    msg = res.data.data.msg
			console.log('上传成功')
		} else {
			msg = res.data.msg
			console.log(msg)
		}
	}).catch(err => {
		    console.log(err)
			this.$refs.upload.clearFiles()
			this.fileList = []
	})
}

4. 定义一个按钮点击事件,点击上传按钮触发

submitUpload() {
    // 判断是否选择了文件
	if (this.fileList.length < 1) {
		 console.log('请先选择本地文件')
	}
	this.$confirm('是否确定上传?', '温馨提示', {
		type: 'warning',
		closeOnClickModal: false
	}).then(() => {
        // 使用upload组件的submit方法触发自定义文件上传函数uploadHttpRequest
		this.$refs.upload.submit()
	})
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值