vue3+ts+vite+elementPlus实现文件上传导入excle给后端,并且清空上传文件后的列表,以及formData变成[object FormData]的解决方法

一、文件上传

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

 2.用vue的axios发起post请求:

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

<el-dialog v-model="dialogFormVisible" title="数据导入" id="input">
      <el-form :model="form">
        <el-form-item label="输入日期" :label-width="formLabelWidth">
          <el-input v-model="form.time" autocomplete="off"  placeholder="XXXX年X月X日"/>
        </el-form-item>
      </el-form>
      <el-form-item label="数据" :label-width="formLabelWidth">
        <el-upload
          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.fileList"
        >
        <el-button type="primary">选择文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="数据" :label-width="formLabelWidth">
        <el-upload
          ref="uploadRef"
          :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-button type="primary">选择文件</el-button>
        </el-upload>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadExcel" @dialogFormVisible="false">
            确认导入
          </el-button>
        </span>
      </template>
      </el-dialog>

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

import {ref, reactive} from 'vue'
import {ElMessage, ElTable,ElUpload, ElButton,ElMessageBox} from 'element-plus'
import type {UploadInstance} from 'element-plus'
import {dataInput} from '@/api/emission';

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

const form = reactive<any>({
  fileList: [],
  files: []
})

 6.之前看了一些上传文件的博客,好像都有const file = new FormData(),于是我也这样写了:

 就发现了上传文件错误:formData变成[object FormData]

FormData 它的基本用法:

FormData 是一个构造函数,new FormData() 即可得到 FormData 对象:

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

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

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

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

7.于是我就改成了以下代码:

 8.成功将文件转换为binary(二进制)并上传给后端!

 9.ts文件上传的完整代码

// 数据导入
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('导入数据成功!');
};
// 文件上传
const uploadExcel = async (file :any) =>{
if(form.time=='' || form.fileList[0]== '' || form.files[0] == '')
return ElMessage.error('日期或者文件不能为空!')
let gasDataFile = form.fileList[0].raw
let electricityDataFile =form.files[0].raw

 await dataInput({time : form.time,gasDataFile,electricityDataFile}).then((res:any) =>{
 if(res.message=='成功'){
    ElMessage.success('导入成功!');
    dialogFormVisible.value=false
 }else{
    ElMessage.error('导入失败!')
 }
})
getList()
if(gasDataFile!== '')
{
  form.time=''
  uploadRefs.value?.clearFiles()
}
if(electricityDataFile!== '')
{
  uploadRef.value?.clearFiles()
}
}

二、清空文件上传的列表

post请求成功后,清空文件上传的列表用clearFiles():

(1)因为我这里上传了两个文件,但清空方法都一样,所以以下我只举列了一个文件列表清空的方法:

先写ref="uploadRef(名字自取,但是不能写upload,它应该是关键字)",

 ref="uploadRef"

 (2)引用并调用外部方法:

import type {UploadInstance} from 'element-plus'

const uploadRefs = ref<UploadInstance>()

 

 (3)使用清空文件上传的clearFiles():

uploadRef.value?.clearFiles()

将会成功清除!

要使用Vue 3TypeScript、setup语法糖、ElementPlus、Flask和PostgreSQL实现上传xlsx文件并插入到数据库,可以按照以下步骤进行: ### 前端部分(Vue 3 + TypeScript + setup语法糖 + ElementPlus) 1. **创建项目** 使用Vue CLI创建一个新的Vue 3项目,并选择TypeScriptVue Router。 ```bash vue create my-project --default cd my-project ``` 2. **安装依赖** 安装ElementPlus和相关的库。 ```bash npm install element-plus @element-plus/icons-vue npm install axios xlsx ``` 3. **配置ElementPlus** 在`main.ts`中配置ElementPlus。 ```typescript import { createApp } from &#39;vue&#39; import App from &#39;./App.vue&#39; import ElementPlus from &#39;element-plus&#39; import &#39;element-plus/dist/index.css&#39; const app = createApp(App) app.use(ElementPlus) app.mount(&#39;#app&#39;) ``` 4. **创建上传组件** 在`src/components`目录下创建`UploadXlsx.vue`组件。 ```vue <template> <div> <el-upload action="#" :on-change="handleChange" :before-upload="beforeUpload" :show-file-list="false" accept=".xlsx" > <el-button type="primary">上传XLSX文件</el-button> </el-upload> </div> </template> <script lang="ts" setup> import { ref } from &#39;vue&#39;; import axios from &#39;axios&#39;; const file = ref<File | null>(null); const beforeUpload = (uploadFile: File): boolean => { file.value = uploadFile; return false; }; const handleChange = async () => { if (file.value) { const formData = new FormData(); formData.append(&#39;file&#39;, file.value); try { const response = await axios.post(&#39;http://localhost:5000/upload&#39;, formData, { headers: { &#39;Content-Type&#39;: &#39;multipart/form-data&#39; } }); console.log(response.data); } catch (error) { console.error(error); } } }; </script> ``` ### 后端部分(Flask + PostgreSQL) 1. **创建Flask项目** 创建一个新的Python项目,并安装所需的库。 ```bash mkdir flask-backend cd flask-backend python -m venv venv source venv/bin/activate pip install flask flask-sqlalchemy psycopg2-binary openpyxl ``` 2. **配置Flask和PostgreSQL** 在`app.py`中配置Flask和PostgreSQL。 ```python from flask import Flask, request from flask_sqlalchemy import SQLAlchemy import openpyxl app = Flask(__name__) app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;postgresql://username:password@localhost:5432/your_database&#39; db = SQLAlchemy(app) class Data(db.Model): id = db.Column(db.Integer, primary_key=True) # 根据实际需求添加更多字段 column1 = db.Column(db.String(255)) @app.route(&#39;/upload&#39;, methods=[&#39;POST&#39;]) def upload(): file = request.files[&#39;file&#39;] if file and file.filename.endswith(&#39;.xlsx&#39;): wb = openpyxl.load_workbook(file) sheet = wb.active for row in sheet.iter_rows(min_row=2, values_only=True): data = Data(column1=row[0]) db.session.add(data) db.session.commit() return &#39;文件上传并插入数据库成功&#39; return &#39;无效的文件&#39; if __name__ == &#39;__main__&#39;: with app.app_context(): db.create_all() app.run(debug=True) ``` ### 运行项目 1. **启动后端** 在`flask-backend`目录下运行Flask应用。 ```bash python app.py ``` 2. **启动前端** 在Vue项目根目录下运行开发服务器。 ```bash npm run serve ``` 通过以上步骤,就可以实现使用Vue 3TypeScript、setup语法糖、ElementPlus、Flask和PostgreSQL上传xlsx文件并插入到数据库。
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Chen__FY

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

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

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

打赏作者

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

抵扣说明:

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

余额充值