<template>
<div style="width: 100%;height: 100%;">
<el-upload
style="width: 100%;height: 100%;"
:class="{disUnloadSty:noneBtnImg}"
action="#"
ref="my-upload"
:before-upload="handleBefore"
:http-request="beforeUpload"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-exceed="handleExceed"
:limit="limit"
:file-list="fileList"
>
<i class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<!--放大-->
<el-dialog :append-to-body="true" :visible.sync="dialogVisible" style="width: 1500px;margin:0 auto">
<div>
<img width="100%" :src="dialogImageUrl" alt="">
</div>
</el-dialog>
</div>
</template>
<script>
/**
* @单张图片上传组件
* */
import request from "../../utils/request";
/**
* 安装oss npm install ali-oss --save
* 详见https://help.aliyun.com/document_detail/32068.html
* */
import OSS from "ali-oss"; // 引入oss
/**
* 安装nanoid插件 npm i nanoid
* https://blog.csdn.net/m0_56219678/article/details/123083541
* */
import {nanoid} from 'nanoid'
export default {
name: 'Uploads',
props:{
// 限制文件上传个数 父子组件调用时可传此值
limit:{
type:Number,
default:1
},
text:{
type:String,
default:'',
}
},
model:{
prop:'text',
event:'change'
},
data: function() {
return {
// fileList:[{name:"123",url:"https://juxin2-test-common.oss-cn-beijing.aliyuncs.com/2022-04-298561rIKROZEZ58NHoNxCT.jpg"}],
fileList:[],
beforefileList:[],
noneBtnImg: false,
dialogImageUrl: '',//图片地址
dialogVisible: false,//图片弹框
}
},
methods: {
/**
* 获取时间 yyyy-mm-dd格式
* */
getTime(){
let date = new Date();//当前时间
let year = date.getFullYear() //返回指定日期的年份
let month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1):`0${date.getMonth() + 1}`;//月
let day = date.getDate() > 9 ? date.getDate():`0${date.getDate()}`;//日
return `${year}/${month}/${day}/`
},
/**
* element上传自定义
* 上传事件
* */
beforeUpload(file){
const OSS = require('ali-oss');
this.fileList = JSON.parse(JSON.stringify(this.beforefileList))
// 请求后台返回信息
request.post("/file/thirdUpload").then((token) => {
const { accessKeyId,accessKeySecret,securityToken }=token.data.credentials
// 初始化client
const client = new OSS({
// yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
endpoint: 'https://oss-cn-beijing.aliyuncs.com', // 或region: 'oss-cn-beijing' 使用region返回的文件链接为http
accessKeyId: accessKeyId,
accessKeySecret:accessKeySecret,
stsToken:securityToken,
// OSS 存储区域名
bucket: "juxin2-test-common",
});
// 获取文件后缀
const tmp = file.file.name.split('.');
const extname = tmp.pop(); // extname 为文件后缀使用此变量也可判断文件类型
// nanoid()为nanoid生成的随机id 随机id按自己项目需求自定义
const path = `juxin-back/${this.getTime()}${nanoid()}.${extname}`; // 文件名格式 时间+随机id+文件类型
// console.log(path)
client.multipartUpload(path, file.file).then(res => { // 开始上传
if (res.res.requestUrls.length>0){ // 上传成功 也可以使用res中的其他参数判断
// this.$message.success('上传成功')
// 去除 oss 分片上传后返回所带的查询参数,否则访问会 403
const ossPath = res.res.requestUrls[0].split('?')[0]; // ossPath就是文件的链接
this.$emit('addressImg',ossPath)
this.$emit('change',ossPath)
this.noneBtnImg = true
this.fileList.push({name:`${this.getTime()}${nanoid()}.${extname}`,url:ossPath})
}
})
})
},
/**
* 文件上传前的回调
* 解决多文件/图片上传时 列表显示问题
* */
handleBefore() {
this.beforefileList = JSON.parse(JSON.stringify(this.fileList))
},
/** 删除图片*/
handleRemove(file) {
this.fileList=this.fileList.filter(i=>{
return i.url!==file.url
})
this.noneBtnImg = false
},
/**
* 文件超出个数限制时的钩子
* */
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 ${this.limit} 个文件`);
},
/** 查看放大图片 */
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url
this.dialogVisible = true
},
/** 清空列表图片地址*/
voidListUrl(){
this.fileList=[]
this.noneBtnImg=false
},
/** 显示图片*/
compileImgShow(val){
this.fileList.push({ name:'', url:val });
this.noneBtnImg=true
this.dialogImageUrl=val
}
}
}
</script>
<style scoped>
/*图标+的位置调整*/
.el-icon-plus{
position: relative;
top:30%;
}
/*提示文字的位置调整*/
/*.el-upload__logo {*/
/* position: absolute;*/
/* top:25px;*/
/* left:0;*/
/* right:0;*/
/* font-size: 12px;*/
/*}*/
/*上传组件设置宽高*/
/deep/.el-upload--picture-card{
/*position: relative;*/
width: 100%;
height: 100%;
line-height: 100%;
}
/*上传图片过程中需要给个高度*/
/*/deep/.disUnloadSty{*/
/* min-height: 120px;*/
/*}*/
/* 上传组件隐藏 */
/deep/ .disUnloadSty .el-upload--picture-card {
display: none;
}
/*图片列表展示的宽高*/
/deep/ .disUnloadSty .el-upload-list__item {
width: 100%;
height: 100%;
display: block;
margin: 0;
transition: none;
}
/* 去除删除图片时的动画*/
/deep/.el-upload-list__item{
transition: none;
}
</style>
阿里云oss+elementui上传组件实现文件上传
最新推荐文章于 2023-03-30 16:53:17 发布