vue3+ts+vite+elementPlus实现文件上传导入excle给后端,s上传文件为二进制格式

一、文件上传

1.首先我们文件上传的方法用到的是multipart/form-data,它是基于post方法来传递数据的,需求是实现类似与这样的:来一个弹框实现两个excel的文件导入

2.封装接口的时候一定要写请求头

3. 引用elementPlus组件中的upload,注意:upload有默认的上传文件方式,并且是数组类型

<div>
				<el-upload
					class="upload-demo"
					drag
					multiple
					ref="uploadRefs"
					:limit="1"
					:auto-upload="false"
					action=""
					accept=".xlsx, .xls"
					:on-exceed="exceedFile"
					:on-error="handleError"
					:on-success="handleSuccess"
					:before-upload="beforeUPload"
					:show-file-list="true"
					v-model:file-list="form.files"
				>
					<el-icon class="el-icon--upload"><upload-filled /></el-icon>
					<div class="el-upload__text">上传表格 <em>请选择</em></div>
					<template #tip>
						<div class="el-upload__tip"></div>
					</template>
				</el-upload>
			</div>

			<footer style="text-align: right; margin-top: 20px">
				<el-button type="primary" 
				:disabled="!workTypeConf.workType && !workTypeConf.workSort"
				 @click="handleStartOrder">开始派单</el-button>
			</footer>

4.在ts中先导入以下东西:

import { useMerDispatchApi1, useMerDispatchApi } from '@/api/terminal/terminal'

import { ElMessage, ElTable, ElUpload, ElButton, ElMessageBox } from 'element-plus'

 5.在from表单中接收上传文件的数组:

// 批量派单
const form = reactive<any>({
	files: []
})

// 数据导入
const beforeUPload = (file: any) => {
	const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
	if (!isExcel)
		ElMessageBox({
			title: '温馨提示',
			message: '上传文件只能是 xls / xlsx 格式!',
			type: 'warning'
		})
	return isExcel
}
// 文件数超出提示
const exceedFile = () => {
	ElMessage.warning('最多只能上传一个文件!')
}
// 上传错误提示
const handleError = () => {
	ElMessage.error('导入数据失败,请您重新上传!')
}
//上传成功提示
const handleSuccess = () => {
	ElMessage.success('导入数据成功!')
}

6.注意在上传的时候一定要把这个文件带给后端我事这样写的希望对你有帮助

 

if (form.files[0] == '') return ElMessage.error('文件不能为空!')
			let file = form.files[0].raw

			const res: any = await useMerDispatchApi({ taskId, 
				userId: row.id, workType, endTime, workSort, workSource, remark, file })

7上传成功后就是这样的结果

注意

FormData 它的基本用法:
FormData 是一个构造函数,new FormData() 即可得到 FormData 对象:

const fd = new FormData() // 创建一个空白的 FormData 对象,里面没有包含任何数据。

调用 FormData 对象的 append(键, 值) 方法,可以向空白的 FormData 中追加键值对数据

但是事实上element Plus里的upload组件里面已经有写好的文件上传方法

并不需要我们再次将获取到的文件变为二进制,然后上传

有啥问题随时联系我就行,看到就回答你,希望可以帮助到你们! 


 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子伟-H5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值