Vue2文件上传相关

导入弹窗


<template><el-dialog:title="title":visible.sync="fileUploadVisible"append-to-bodyclose-on-click-modalclose-on-press-escapewidth="420px"><div v-if="showDatePicker">选择时间:<el-date-pickerv-model="dataDate"type="date"placeholder="选择日期"value-format="yyyy-MM-dd"format="yyyy-MM-dd"></el-date-picker></div><div class="my-upload"><el-uploadclass="upload-file-uploader"ref="fileUpload"multipledrag:action="uploadFileUrl":before-upload="handleBeforeUpload":file-list="fileList":limit="limit":on-error="handleUploadError":on-exceed="handleExceed":on-success="handleUploadSuccess":show-file-list="false":headers="headers":data="infoType"><i class="el-icon-upload"></i><div class="el-upload__text">将文件拖到此处,或<em style="color: rgb(22, 93, 255)">点击上传</em></div></el-upload><!-- 文件列表 --><transition-groupclass="upload-file-list el-upload-list el-upload-list--text"name="el-fade-in-linear"tag="ul"><li:key="file.url"class="el-upload-list__item ele-upload-list__item-content"v-for="(file, index) in fileList"><el-link :href="file.url" :underline="false" target="_blank"><span class="el-icon-document"> {{ getFileName(file.name) }} </span></el-link><div class="ele-upload-list__item-content-action"><el-link:underline="false"@click="handleDelete(index)"type="danger">删除</el-link></div></li></transition-group></div><div style="text-align: center; padding: 15px">点击右侧按钮,下载导入模板<span class="import-text" v-if="showDownLoad" @click="onDownLoad">下载</span></div><div class="tip-text" v-if="tipText"><span>特别提醒:</span>{{ tipText }}</div></el-dialog>
</template>
<script>
import dayjs from "dayjs";
import { saveAs } from "file-saver";
import { getToken } from "@/utils/auth";export default {props: {title: {type: String,default: "导入",},tipText: {type: String,default: "",},// 值value: [String, Object, Array],// 数量限制limit: {type: Number,default: 99,},// 文件类型, 例如['png', 'jpg', 'jpeg']fileType: {type: Array,default: () => ["xls", "xlsx"],// default: () => ["png", "jpg", "jpeg"],},// 下载模版apidownloadApi: {type: Function,default: () => {console.log("[  ] >", "downloadApi");},},// 下载模板标题downloadTitle: {type: String,default: "导入模板",},// 导入apiimportApi: {type: Function,default: () => {console.log("[  ] >", "importApi");},},// 是否真是下载模板showDownLoad: {type: Boolean,default: true,},showDatePicker: {type: Boolean,default: false,},// 模板下载地址uploadUrl: { type: String, default: "" },// 导入需要的InfoTypeinfoType: {type: Object,default: () => {},},},data() {return {number: 0,uploadList: [],uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传文件服务器地址headers: {Authorization: "Bearer " + getToken(),},fileList: [],fileUploadVisible: false,file: null,dataDate: "",};},mounted() {},watch: {value: {handler(val) {if (val) {let temp = 1;// 首先将值转为数组const list = Array.isArray(val) ? val : this.value.split(",");// 然后将数组转为对象数组this.fileList = list.map((item) => {if (typeof item === "string") {item = { name: item, url: item };}item.uid = item.uid || new Date().getTime() + temp++;return item;});} else {this.fileList = [];return [];}},deep: true,immediate: true,},},methods: {onShow() {this.fileUploadVisible = true;console.log(process.env.VUE_APP_BASE_API + "/file/upload");this.dataDate = "";},// 下载模版onDownLoad() {this.downloadApi().then((res) => {const blob = new Blob([res]);saveAs(blob, `${this.downloadTitle}.xlsx`);});},// 上传前校检格式和大小handleBeforeUpload(file) {if (this.showDatePicker && this.dataDate == "") {this.$message.warning("请先选择日期");} else {// 校检文件类型if (this.fileType) {const fileName = file.name.split(".");const fileExt = fileName[fileName.length - 1];const isTypeOk = this.fileType.indexOf(fileExt) >= 0;if (!isTypeOk) {this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);return false;}}this.file = file;this.$modal.loading("正在上传文件,请稍候...");this.number++;return true;}},// 文件个数超出handleExceed() {this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);},// 上传失败handleUploadError(err) {this.$modal.msgError("上传文件失败,请重试");this.$modal.closeLoading();},// 上传成功回调handleUploadSuccess(res, file) {if (this.showDatePicker && this.dataDate == "") {} else {if (res.code == 200) {const formData = new FormData();formData.append("file", this.file);if (this.showDatePicker) {formData.append("dataDate", this.dataDate);}this.importApi(formData).then((res) => {if (res.code == 0 || res.code == 200) {this.$message.success("导入成功");this.uploadList = [];this.fileList = [];this.fileUploadVisible = false;this.$modal.closeLoading();this.$emit("getList");}}).catch(() => {this.$modal.closeLoading();});return;}this.$modal.msgError("上传文件失败,请重试");this.$modal.closeLoading();}},// 删除文件handleDelete(index) {this.fileList.splice(index, 1);this.$emit("input", this.listToString(this.fileList));},// 上传结束处理uploadedSuccessfully() {if (this.number > 0 && this.uploadList.length === this.number) {this.fileList = this.fileList.concat(this.uploadList);this.uploadList = [];this.number = 0;this.$emit("input", this.listToString(this.fileList));this.$modal.closeLoading();}},// 获取文件名称getFileName(name) {// 如果是url那么取最后的名字 如果不是直接返回if (name?.lastIndexOf("/") > -1) {return name.slice(name.lastIndexOf("/") + 1);} else {return name;}},// 对象转成指定字符串分隔listToString(list, separator) {let strs = "";separator = separator || ",";for (let i in list) {strs += list[i].url + separator;}return strs != "" ? strs.substr(0, strs.length - 1) : "";},},
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__header > .el-dialog__title {font-weight: 600 !important;
}.import-text {color: rgb(22, 93, 255);text-align: center;font-size: 14px;cursor: pointer;
}.my-upload {margin-top: 20px;display: flex;justify-content: center;.el-icon-upload {color: rgb(22, 93, 255);font-size: 100px;}
}.tip-text {padding: 0 10px;margin-top: 20px;color: rgb(241, 51, 51);
}.upload-file-uploader {margin-bottom: 5px;
}.upload-file-list .el-upload-list__item {border: 1px solid #e4e7ed;line-height: 2;margin-bottom: 10px;position: relative;
}.upload-file-list .ele-upload-list__item-content {display: flex;justify-content: space-between;align-items: center;color: inherit;
}.ele-upload-list__item-content-action .el-link {margin-right: 10px;
}:v-deep .el-upload,
.el-upload--text {// margin: 0 auto !important;width: 100% !important;
}
</style>

弹窗使用

 <!-- 导入 -->
<FileUploadref="fileUpload"title="导入数据":importApi="importRealApi":onReset="getRealList"@getList="getList":infoType="infoType":downloadApi="downRealTempleteApi":showDatePicker="true":tipText="tipText"downloadTitle="房产交易信息导入模板"
/>

1.为什么要进行 const formData = new FormData() 处理

HTTP 请求中,文件不能直接作为普通文本字段发送,需要以二进制流的形式上传。FormData 专门用于构造包含文件的表单数据,浏览器会自动将其编码成 multipart/form-data 格式,符合文件上传的标准

2.multipart/form-data 格式是什么  

multipart/form-data 是一种专门为上传文件设计的 HTTP 请求编码格式,它通过分隔符将多个字段(包括文件)分开,保证文件数据能被正确传输和解析,是文件上传的标准方式。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/web/90991.shtml
繁体地址,请注明出处:http://hk.pswp.cn/web/90991.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vue使用xlsx库导出excel

引入xlsx库 import XLSX from "xlsx";将后端接口返回的数据和列名&#xff0c;拼接到XLSX.utils.aoa_to_sheet中exportExcel() {debugger;if (!this.feedingTableData || this.feedingTableData.length "0") {this.$message.error("投料信息为空&…

卷积神经网络(CNN)处理流程(简化版)

前言 是看了这个大佬的视频后想进行一下自己的整理&#xff08;流程只到了扁平化&#xff09;&#xff0c;如果有问题希望各位大佬能够给予指正。卷积神经网络&#xff08;CNN&#xff09;到底卷了啥&#xff1f;8分钟带你快速了解&#xff01;_哔哩哔哩_bilibilihttps://www.…

DBSyncer:开源免费的全能数据同步工具,多数据源无缝支持!

DBSyncer&#xff08;英[dbsɪŋkɜː]&#xff0c;美[dbsɪŋkɜː 简称dbs&#xff09;是一款开源的数据同步中间件&#xff0c;提供MySQL、Oracle、SqlServer、PostgreSQL、Elasticsearch(ES)、Kafka、File、SQL等同步场景。支持上传插件自定义同步转换业务&#xff0c;提供…

kafka开启Kerberos使用方式

kafka SASL_PLAINTEXT serviceName 配置&#xff1a; /etc/security/keytabs/kafka.service.keytab 对应的用户名 $ cat /home/sunxy/kafka/jaas25.conf KafkaClient { com.sun.security.auth.module.Krb5LoginModule required useKeyTabtrue renewTickettrue serviceName“ocd…

Unity教程(二十四)技能系统 投剑技能(中)技能变种实现

Unity开发2D类银河恶魔城游戏学习笔记 Unity开发2D类银河恶魔城游戏学习笔记目录 技能系统 Unity教程&#xff08;二十一&#xff09;技能系统 基础部分 Unity教程&#xff08;二十二&#xff09;技能系统 分身技能 Unity教程&#xff08;二十三&#xff09;技能系统 掷剑技能…

局域网TCP通过组播放地址rtp推流和拉流实现实时喊话

应用场景&#xff0c;安卓端局域网不用ip通过组播放地址实现实时对讲功能发送端: ffmpeg -f alsa -i hw:1 -acodec aac -ab 64k -ac 2 -ar 16000 -frtp -sdp file stream.sdp rtp://224.0.0.1:14556接收端: ffmpeg -protocol whitelist file,udp,rtp -i stream.sdp -acodec pcm…

基于深度学习的医学图像分析:使用YOLOv5实现细胞检测

最近研学过程中发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击链接跳转到网站人工智能及编程语言学习教程。读者们可以通过里面的文章详细了解一下人工智能及其编程等教程和学习方法。下面开始对正文内容的…

32.768KHZ 3215晶振CM315D与NX3215SA应用全场景

在现代电子设备中&#xff0c;一粒米大小的晶振&#xff0c;却是掌控时间精度的“心脏”。CITIZEN的CM315D系列与NDK的NX3215SA系列晶振便是其中的佼佼者&#xff0c;它们以 3.2 1.5 mm 的小尺寸”(厚度不足1mm)&#xff0c;成为智能设备中隐形的节奏大师。精准计时的奥秘这两…

嵌软面试——ARM Cortex-M寄存器组

Cortex-M内存架构包含16个通用寄存器&#xff0c;其中R0-R12是13个32位的通用寄存器&#xff0c;另外三个寄存器是特殊用途&#xff0c;分别是R13&#xff08;栈指针&#xff09;,R14&#xff08;链接寄存器&#xff09;,R15&#xff08;程序计数器&#xff09;。对于处理器来说…

7.DRF 过滤、排序、分页

过滤Filtering 对于列表数据可能需要根据字段进行过滤&#xff0c;我们可以通过添加django-fitlter扩展来增强支持。 pip install django-filter在配置文件中增加过滤器类的全局设置&#xff1a; """drf配置信息必须全部写在REST_FRAMEWORK配置项中""…

二、CUDA、Pytorch与依赖的工具包

CUDA Compute Unified Device Architecture&#xff08;统一计算架构&#xff09;。专门用于 GPU 通用计算 的平台 编程接口。CUDA可以使你的程序&#xff08;比如矩阵、神经网络&#xff09;由 GPU 执行&#xff0c;这比CPU能快几十甚至上百倍。 PyTorch 是一个深度学习框架…

SpringCloude快速入门

近期简单了解一下SpringCloude微服务,本文主要就是我学习中所记录的笔记,然后具体原理可能等以后再来深究,本文可能有些地方用词不专业还望包容一下,感兴趣可以参考官方文档来深入学习一下微服务,然后我的下一步学习就是docker和linux了。 nacos: Nacos 快速开始 | Nacos 官网…

GPT Agent与Comet AI Aent浏览器对比横评

1. 架构设计差异GPT Agent的双浏览器架构&#xff1a;文本浏览器&#xff1a;专门用于高效处理大量文本内容&#xff0c;适合深度信息检索和文献追踪&#xff0c;相当于Deep Research的延续可视化浏览器&#xff1a;具备界面识别与交互能力&#xff0c;可以点击网页按钮、识别图…

应用信息更新至1.18.0

增加DO权限 增加权限管理&#xff08;需DO支持&#xff09; 增加应用冻结隐藏&#xff08;需DO支持&#xff09; 增加权限委托&#xff08;需DO支持&#xff09; 增加特殊组件 ...

常用git命令集锦

git init 初始化 将当前目录初始化为 git 本地仓库&#xff0c;此时会在本地创建一个 .git 的文件夹 git init -q 静默执行&#xff0c;就是在后台执行 git init --bare –bare 参数,一般用来初始化一个空的目录&#xff0c;作为远程存储仓库 git init --template dir –templa…

skywalking安装

一、简介 SkyWalking是一款用于分布式系统跟踪和性能监控的开源工具。它可以帮助开发人员了解分布式系统中不同组件之间的调用关系和性能指标&#xff0c;从而进行故障排查和性能优化。 它支持多种语言和框架&#xff0c;包括Java、.NET、Node.js等。它通过在应用程序中插入代…

利用DataStream和TrafficPeak实现大数据可观察性

可观察性工作流对于深入了解应用程序的健康状况、客户流量和整体性能至关重要。然而&#xff0c;要实现真正的可观察性还面临一些挑战&#xff0c;包括海量的流量数据、数据保留、实施时间以及各项成本等。TrafficPeak是一款为Akamai云平台打造&#xff0c;简单易用、可快速部署…

jQuery 最新语法大全详解(2025版)

引言 jQuery 作为轻量级 JavaScript 库&#xff0c;核心价值在于 简化 DOM 操作、跨浏览器兼容性和高效开发。尽管现代框架崛起&#xff0c;jQuery 仍在遗留系统维护、快速原型开发中广泛应用。本文涵盖 jQuery 3.6 核心语法&#xff0c;重点解析高效用法与最佳实践。 一、jQu…

Android 15 修改截图默认音量大小

概述 在 Android 15 中,截图音效的默认音量可能过大,影响用户体验。本文将介绍如何通过修改系统源码来调整截图音效的默认音量大小。 修改位置 需要修改的文件路径: frameworks/base/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotSoundProvider.kt…

Python爬虫实战:快速采集教育政策数据(附官网工具库API)

解锁教育政策研究的数据金矿&#xff0c;用技术提升学术效率 在教育政策研究领域&#xff0c;获取最新、最全面的政策文本是学术工作的基础。传统手动收集方式效率低下且容易遗漏关键政策&#xff0c;而Python爬虫技术为教育研究者提供了高效的数据采集解决方案。本文将系统介…