vue项目使用elementUI的el-upload组件实现图片上传和文件上传的公共组件封装
图片上传:
<template>
<div class="upload-pic">
<el-upload
class="upload-demo"
:action="uploadFdfsFileUrl"
:headers="requestHeader"
list-type="picture-card"
name="file"
:before-upload="beforeAvatarUpload"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:on-success="handleSuccess"
:on-error="handleError"
:multiple="multiple"
:limit="limitNum"
:on-exceed="handleExceed"
:file-list.sync="picWebUrlList"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
</div>
</template>
import { mapGetters, mapActions } from 'vuex'
import { getToken } from '@/utils/auth'
export default {
name: 'UploadPic',
props: {
isEdit: {
type: Boolean,
default: false
},
// 是否多选
multiple: {
type: Boolean,
default: true
},
// 文件列表
fileList: {
type: Array,
default: () => []
},
// 限制上传个数
limitNum: {
type: Number,
default: null
}
},
data() {
return {
// 附件上传请求头
requestHeader: '',
// 图片上传路径
picUploadList: [],
// 图片回显路径
picWebUrlList: [],
// 预览路径
dialogImageUrl: '',
// 预览弹框
dialogVisible: false,
// 删除图片下标
delIndex: null
}
},
computed: {
...mapGetters([
'uploadFdfsFileUrl'
])
},
watch: {},
/**
* 生命周期函数--el 被新创建的 vm.$el 替换,并挂载到实例上去之后调用该钩子
*/
mounted: function() {},
created() {
// 设置文件按上传请求头
this.requestHeader = { 'Authorization': 'Bearer ' + getToken('token') }
},
methods: {
...mapActions([
'download'
]),
refreshPicData(value) {
this.picUploadList = value
this.getWebUrlList()
},
// 图片回显数组
getWebUrlList() {
let webUrlList = []
if (this.picUploadList.length > 0) {
this.picUploadList.forEach((item, index) => {
// 获取图片 web 地址
this.$store.dispatch('dictionary/getWebFileUrl', item.url).then(response => {
const fileObj = {
index: index,
name: '',
url: response.data
}
webUrlList.push(fileObj)
})
})
this.picWebUrlList = webUrlList
}
},
// 图片格式及大小限制
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpg'
const isJPEG = file.type === 'image/jpeg'
const isGIF = file.type === 'image/gif'
const isPNG = file.type === 'image/png'
const isBMP = file.type === 'image/bmp'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG && !isJPEG && !isGIF && !isPNG && !isBMP) {
this.$message.error('上传图片必须是JPG/JPEG/GIF/PNG/BMP 格式!')
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!')
}
return (isJPG || isJPEG || isBMP || isGIF || isPNG) && isLt2M
},
// 点击预览图标,预览图片
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url
this.dialogVisible = true
},
// 文件列表移除文件时的钩子
handleRemove(file, fileList) {
if (this.isEdit) {
this.picUploadList.splice(this.delIndex, 1)
this.$emit('update:fileList', this.picUploadList)
} else {
const fileArr = []
fileList.forEach(item => {
if (item.response) {
const fileObj = {
name: item.name,
url: item.response.data
}
fileArr.push(fileObj)
} else {
fileArr.push(item)
}
})
this.$emit('update:fileList', fileArr)
}
},
// 删除文件之前的钩子
beforeRemove(file, fileList) {
fileList.forEach((item, index) => {
if (file.url === item.url) {
this.delIndex = index
}
})
return this.$confirm('', `确定移除 ${file.name}?`, { customClass: 'del-dialog' })
},
// 文件上传成功时的钩子
handleSuccess(response, file, fileList) {
if (response.code === '1') {
if (this.isEdit) {
const fileObj = {
index: this.picUploadList.length,
name: file.name,
url: response.data
}
this.picUploadList.push(fileObj)
this.$emit('update:fileList', this.picUploadList)
} else {
const fileArr = []
fileList.forEach(item => {
if (item.response) {
const fileObj = {
name: item.name,
url: item.response.data
}
fileArr.push(fileObj)
} else {
fileArr.push(item)
}
})
this.$emit('update:fileList', fileArr)
}
} else {
this.$message({
message: `${file.name} 上传失败,请重新再试`,
type: 'error',
duration: 2000
})
}
},
// 文件上传失败时的钩子
handleError(err, file, fileList) {
console.log(err)
this.$message({
message: `${file.name} 上传失败,请重新再试`,
type: 'error',
duration: 2000
})
},
// 文件超出个数限制时的钩子
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 ${this.limitNum} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
}
}
}
父组件引用:<upload-pic ref="refreshData" :file-list.sync="formData.picList" :limit="1" :is-edit="isEdit"></upload-pic>
在编辑图片时,将编辑图片的数组传递给图片上传组件,否则不能回显
父组件拿到图片数据后,通过调用图片上传组件内的 refreshPicData 方法,传递图片数据。
文件上传:
<template>
<div class="upload-file">
<el-upload
class="upload-demo"
:action="uploadFdfsFileUrl"
:headers="requestHeader"
name="file"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:on-success="handleSuccess"
:on-error="handleError"
:multiple="multiple"
:limit="limitNum"
:on-exceed="handleExceed"
:file-list.sync="fileList"
>
<el-button class="dashed-btn" icon="el-icon-upload" size="small">{{ btnTxt }}</el-button>
<div slot="tip" class="el-upload__tip">{{ tipTxt }}</div>
</el-upload>
</div>
</template>
import { mapGetters, mapActions } from 'vuex'
import { getToken } from '@/utils/auth'
export default {
name: 'UploadFile',
props: {
// 是否多选
multiple: {
type: Boolean,
default: true
},
// 文件列表
fileList: {
type: Array,
default: () => []
},
// 限制上传个数
limitNum: {
type: Number,
default: null
},
// 按钮文字
btnTxt: {
type: String,
default: '上传附件'
},
// tip 提示
tipTxt: {
type: String,
default: ''
}
},
data() {
return {
// 附件上传请求头
requestHeader: ''
// 限制文件数量
// limitNum: ''
// 文件列表
// fileList: []
}
},
computed: {
...mapGetters([
'uploadFdfsFileUrl'
])
},
watch: {},
/**
* 生命周期函数--el 被新创建的 vm.$el 替换,并挂载到实例上去之后调用该钩子
*/
mounted: function() {},
created() {
// 设置文件按上传请求头
this.requestHeader = { 'Authorization': 'Bearer ' + getToken('token') }
},
methods: {
...mapActions([
'download'
]),
// 点击文件列表中已上传的文件时的钩子,下载文件
handlePreview(file) {
console.log(file)
// const param = {
// fileUrl: file.url
// }
// this.$store.dispatch('dictionary/downLoad', param).then(response => {
// console.log(response)
// let fileName = localStorage.fileName
// fileName = decodeURI(fileName.substr(fileName.indexOf('=') + 1))
// const paramData = {
// data: response,
// title: '天津园区电梯监控.xlsx'
// }
// this.download(paramData)
// })
},
// 文件列表移除文件时的钩子
handleRemove(file, fileList) {
const fileArr = []
fileList.forEach(item => {
if (item.response) {
const fileObj = {
name: item.name,
url: item.response.data
}
fileArr.push(fileObj)
} else {
fileArr.push(item)
}
})
this.$emit('update:fileList', fileArr)
},
// 删除文件之前的钩子
beforeRemove(file, fileList) {
return this.$confirm('', `确定移除 ${file.name}?`, { customClass: 'del-dialog' })
},
// 文件上传成功时的钩子
handleSuccess(response, file, fileList) {
if (response.code === '1') {
const fileArr = []
fileList.forEach(item => {
if (item.response) {
const fileObj = {
name: item.name,
url: item.response.data
}
fileArr.push(fileObj)
} else {
fileArr.push(item)
}
})
this.$emit('update:fileList', fileArr)
} else {
this.$message({
message: `${file.name} 上传失败,请重新再试`,
type: 'error',
duration: 2000
})
}
},
// 文件上传失败时的钩子
handleError(err, file, fileList) {
console.log(err)
this.$message({
message: `${file.name} 上传失败,请重新再试`,
type: 'error',
duration: 2000
})
},
// 文件超出个数限制时的钩子
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 ${this.limitNum} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
}
}
}
父组件引用:<upload-file :file-list.sync="formData.fileList" ></upload-file>
vue项目使用elementUI的el-upload组件实现图片上传和文件上传的公共组件封装的更多相关文章
- vue项目搭建和开发流程 vue项目配置ElementUI、jQuery和Bootstrap环境
目录 一.VUE项目的搭建 1. 环境搭建 2. 项目的创建和启动 二. 开发项目 1. 配置vue项目启动功能 2. 开发vue项目 (1)项目文件的作用 (2)vue项目开发流程 (3)vue项目 ...
- Vue项目引进ElementUI组件
1.https://blog.csdn.net/Mr_JavaScript/article/details/80741914 1.1 安装 npm install element-ui -save 1 ...
- 【vue】vue项目引入 Element-UI
根据vue项目的搭建教程,接下来记录下如何在Vue-cli创建的项目中引入Element-UI. 1.安装直接用命令 (推荐) npm install element-ui 2.直接在根目录下的pac ...
- Java web项目 上传图片保存到数据库,并且查看图片,(从eclipse上移动到tomact服务器上,之路径更改,包括显示图片和导出excel)
//项目做完之后,在本机电脑运行完全正常,上传图片,显示图片,导出excel,读取excel等功能,没有任何问题,但是,当打成war包放到服务器上时,这些功能全部不能正常使用. 最大的原因就是,本机测 ...
- vue项目使用element-ui的Tooltip 无效
我之前要使用vue开发一个项目,使用到了element-UI的Tooltip 组件 <el-tooltip class="item" effect="dark&qu ...
- Vue项目打包发布后CSS中的背景图片不显示
相信有很多同学在学习vue的刚开始都遇到过项目打包发布后发现CSS中的背景图片不显示,具体如何解决只需要更改bind的配置即可 修改 build/utils.js 中的 generateLoaders ...
- vue项目搭建通过vue-cli包括组件路由的使用实现基本的前端项目全流程
github上项目地址:https://github.com/comonly/javaweb_blog/tree/master/blog_diverse_frontend 具体搭建流程及实现方式:ht ...
- vue+element-ui, el-upload组件 文件上传之前return false,会自动调用文件移除回调问题
日常搬砖的时候,项目中在使用element-ui的上传组件,但是当我在文件上传文件之前的回调里面做了些文件格式的二次校验和文件大小的校验的时 然后 return false 会发现调用 文件移除的回调 ...
- vue之element-ui文件上传
vue之element-ui文件上传 文件上传需求 对于文件上传,实际项目中我们的需求一般分两种: 对于单个的文件上传,比如拖动上传个图片之类的,或者是文件. 和表单一起实现上传(这种情况一般都是 ...
- DRF+Vue项目(一)——项目架构
永久配置安装源 为了加速模块的下载 1.文件管理器文件路径地址栏敲:%APPDATA% 回车,快速进入 C:\Users\电脑用户\AppData\Roaming 文件夹中 2.新建 pip 文件夹并 ...
随机推荐
- Python 自动化爬虫利器 Playwright
Python 自动化爬虫利器 Playwright Python Playwright 是一个基于 Node.js 的自动化测试库,它支持多种浏览器(Chrome.Firefox.Safari.Edg ...
- Android 13 - Media框架(4)- MediaPlayerService
关注公众号免费阅读全文,进入音视频开发技术分享群! MediaPlayerService是android的多媒体框架的核心服务之一,该服务存储有android平台所支援的编解码器信息,管理所有通过Me ...
- SQLServer如何监控阻塞会话
一.查询阻塞和被阻塞的会话 SELECT r.session_id AS [Blocked Session ID], r.blocking_session_id AS [Blocking Sessio ...
- Mp4V2与ffmpeg静态库符号冲突问题解决
一.为什么静态符号会冲突 无论macho二进制类型,还是Windows上的PE格式,还是Linux上的ELF格式,里面都是按照特定格式存放的一个程序的代码和数据 比如Linux下的可执行文件格式,大致 ...
- RTMP推流FLV插入自定义SEI数据总结
一.需求 在RTMP推送的流中添加一个接口,可以添加自定义的数据(一段字节数组). 经过分析,在H264的流中可以通过SEI添加自定义数据,下面是实施的总结 二.实施 1)准备工具 RTMP推流客户端 ...
- 设定cookie 获取cookie数据的转换
1,cookie必须是键值对形式的 键名=数值 而且必须是 字符串格式 document.cookie = 'nam ...
- INFINI Labs 产品更新 | Agent 全新重构,优化指标采集,支持集中配置管理,支持动态下发等功能
INFINI Labs 产品又更新啦~ 本次更新主要有 Agent.Console.Loadgen 等产品,其中 Agent 进行全新重构升级,新版限制了 CPU 资源消耗,优化了内存,相比旧版内存使 ...
- .NET5 IIS ASP.NET CORE 部署时 HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure
.NET5 IIS ASP.NET CORE 部署时 HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure 部署机器只安装了dotnet-hos ...
- linux命令查看内存命令free -h whereis locate find查找命令
linux命令查看内存命令free -h whereis locate find查找命令 1.free -h root@hz-auto-eureka-test-03:/usr/local/tomca ...
- Sqlite windows11 安装与使用
首先进入Sqlite官方网址: https://www.sqlite.org/download.html 然后下载下面框起来的两个压缩文件 下载完成后解压 接下来去配置环境变量,右键此电脑->属 ...