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
英文地址,請注明出處:http://en.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爬蟲技術為教育研究者提供了高效的數據采集解決方案。本文將系統介…