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 文件夹并 ...
随机推荐
- 8.4考试总结(NOIP模拟30)[毛一琛·毛二琛·毛三琛]
最有名的莫过于想死一次吗. 前言 至今都不知道题目是个啥... T1 毛一琛 解题思路 \(\mathcal{Meet\;In\;The\;Middle}\) 其实就是一个爆搜... 把整个区间分为两 ...
- this的二种使用方式
package com.ht.TestThis; public class TestThisKey { public static void main(String[] args) { // TODO ...
- 混入 - Mixins
混入(mixins)是一种分发Vue组件中可复用功能的非常灵活的方式.混入对象可以包含任意组件选项.当组件使用混入对象时,所有混入对象的选项将被混入该组件本身的选项. 混入分为:全局和局部 定义全局混 ...
- The remote name could not be resolved
HTTP The remote name could not be resolved HTTP Status:NameResolutionFailure
- spring.jackson 相差8小时,restful接收Date参数处理
spring.jackson 相差8小时,restful接收Date参数处理 前端提交字符串到后台映射日期类型的话,加上@DateTimeFormat(pattern = "yyyy-M ...
- 【长文】带你搞明白Redis
本文使用第一人称来介绍Redis 一.概述 Redis,英文全称是Remote Dictionary Server(远程字典服务),是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化 ...
- Linux安全审计之audit安装与使用
场景 安全最重要的一步是内部安全,如何监控用户的行为是一个永恒不变的话题. audit可以详细监控用户的行为,详细到查看或修改了某个文件.这些都可以在日志中查看到. 安装 小贴士: CentOS默认已 ...
- 配置pod拉取harbor容器镜像仓库私有镜像:secret保存账号密码
目录 一.系统环境 二.前言 三.Docker-Registry类型的Secret简介 四.镜像仓库简介 五.搭建Harbor容器镜像仓库 5.1 安装Harbor 5.2 创建项目 5.3 推送镜像 ...
- VScode连接服务器不用每次都输入密码
VScode连接服务器不用每次都输入密码. 用git或xcode的ssh keygen生成一组不带密码的 rsa2048 的公钥id_rsa_nopasswd.pub和私钥id_rsa_nopassw ...
- 在Markdown中使用base64存图片
author="CKboss" date="2022-4-19" title="在Markdown中使用base64存图片" +++ 在Ma ...