vue+elementUI上传单张、多张图片/视频至oss
1.上传单张图片效果:创建oss.js接口配置文件import request from '@/utils/re.js' //封装的请求文件import axios from 'axios'export function policy1() {return request({url:'url',//接口地址method:'get',})}在components下创建singleUpload.vue
1.上传单张图片
效果:
创建oss.js接口配置文件
import request from '@/utils/re.js' //封装的请求文件
import axios from 'axios'
export function policy1() {
return request({
url:'url',//接口地址
method:'get',
})
}
在components下创建singleUpload.vue组件
<template>
<div>
<!-- 上传单张图片 -->
<el-upload action="填写OSS域名"
:data="dataObj"
class="avatar-uploader"
:file-list="fileList"
:show-file-list="false"
:on-remove="handleRemove"
:on-success="handleUploadSuccess"
:before-upload="beforeUpload">
<img :preview-src-list="dialogImageUrlArr" :width="w" :height="h" v-if="dialogImageUrl" :src="dialogImageUrl" alt="" class="avatar">
<i v-else :style="{fontSize: '18px',fontWeight:'bold',padding:paddings}" class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</template>
<script>
import {policy1} from '@/api/oss'
export default {
name: 'SingleUpload',
props: {
value:{
type:String
},
w:{
type:String,
// default:'100px'
},
h:{
type:String,
// default:'100px'
},
paddings:{
type:String,
}
},
data() {
return {
dataObj: {
policy: '',
signature: '',
key: '',
ossaccessKeyId: '',
dir: '',
host: ''
},
dialogVisible: false,
dialogImageUrl: null,
dialogImageUrlArr:[],
}
},
mounted() {
console.log(this.fileList)
},
computed: {
imageUrl() {
console.log("修改图",this.value);
if(this.value){
this.dialogImageUrl=this.value;
}else{
this.dialogImageUrl='';
}
return this.value;
},
imageName() {
if (this.value != null && this.value !== '') {
return this.value.substr(this.value.lastIndexOf('/') + 1)
} else {
return null
}
},
fileList() {
return [{
name: this.imageName,
url: this.imageUrl
}]
},
showFileList: {
get: function() {
return this.value !== null && this.value !== '' && this.value !== undefined
},
set: function(newValue) {
}
}
},
methods: {
emitInput(val) {
this.$emit('input', val)
},
handleRemove(file, fileList) {
this.emitInput('')
},
handlePreview(file) {
this.dialogVisible = true
},
getUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
},
beforeUpload(file) {
console.log("获取数据前",file);
const _self = this
return new Promise((resolve, reject) => {
policy1().then(response => {
_self.dataObj.policy = response.data.policy;
_self.dataObj.signature = response.data.signature;
_self.dataObj.ossaccessKeyId = response.data.accessKeyId;
_self.dataObj.key = response.data.dir +this.getUUID()+ '_${filename}';
_self.dataObj.dir = response.data.dir;
_self.dataObj.host = response.data.host;
_self.dataObj.callback = response.data.callback;
resolve(true)
}).catch(err => {
console.log(err)
reject(false)
})
})
},
handleUploadSuccess(res, file) {
console.log('上传成功...')
this.showFileList = true
this.fileList.pop();
this.dialogImageUrl = this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name);
this.dialogImageUrlArr.push(this.dialogImageUrl);
console.log("成功",res);
// this.emitInput(this.dialogImageUrl)
this.emitInput(this.dialogImageUrl)
}
}
}
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
/* width: 100%; */
/* height: 100%; */
/* line-height: 178px; */
text-align: center;
}
.avatar {
/* width: 178px; */
/* height: 178px; */
display: block;
}
</style>
页面调用
<single-upload v-model="userImg" w="150px" h="150px" paddings="65px" />
import singleUpload from '../../../components/singleUpload.vue' //单张
export default {
components: {singleUpload},//注册组件
data() {
return {
userImg:''
}
}
}
上传多张图片至oss
效果:效果回显还有一些问题,就是回显的时候会出现闪动,不影响使用,但是体验效果有点不佳。如果有小伙伴完善了,可以给我指导一下吗(主要懒了啊啊啊),谢恩~~~~~
解决方法:上传图片成功后拿到图片路径,自己手写一个图片渲染及删除 ,这是我更新的代码:https://blog.csdn.net/oneya1/article/details/115330235?spm=1001.2014.3001.5501
<template>
<div>
<!-- 上传多张图片 -->
<el-upload action="填写oss域名"
:data="dataObj"
list-type="picture-card"
:file-list="fileList"
:on-remove="handleRemove"
:on-success="handleUploadSuccess"
:before-upload="beforeUpload"
:limit="maxCount"
:on-exceed="handleExceed">
<i class="el-icon-plus" :style="{fontSize: '18px',fontWeight:'bold',padding:paddings}"></i>
</el-upload>
</div>
</template>
<script>
import {
policy1
} from '@/api/oss'
export default {
name: 'SingleUpload',
props: {
value: Array,
//最大上传图片数量
maxCount: {
type: Number,
default: 5
},
w:{
type:String,
// default:'100px'
},
h:{
type:String,
// default:'100px'
},
paddings:{
type:String,
}
},
data() {
return {
dataObj: {
policy: '',
signature: '',
key: '',
ossaccessKeyId: '',
dir: '',
host: ''
},
dialogVisible: false,
dialogImageUrl: null
}
},
computed: {
fileList() {
let fileList = [];
for (let i = 0; i < this.value.length; i++) {
fileList.push({
url: this.value[i]
});
}
return fileList;
}
},
methods: {
getUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
},
emitInput(fileList) {
let value=[];
for(let i=0;i<fileList.length;i++){
value.push(fileList[i].url);
}
this.$emit('input', value)
},
handleRemove(file, fileList) {
this.emitInput(fileList)
},
handleUploadSuccess(res, file) {
console.log('获取图片',res.data);
let url = this.dataObj.host +'/'+ this.dataObj.key.replace('${filename}', file.name);
console.log('路径',url);
// if(!this.useOss){
// //不使用oss直接获取图片路径
// url = res.data.url;
// }
this.fileList.push({
name: file.name,
url: url
});
this.emitInput(this.fileList);
},
beforeUpload(file) {
const _self = this
return new Promise((resolve, reject) => {
policy1().then(response => {
console.log("获取数据", response.data);
_self.dataObj.policy = response.data.policy;
// console.log('policy值',response.data.policy);
_self.dataObj.signature = response.data.signature;
// console.log('signature值',response.data.signature);
_self.dataObj.ossaccessKeyId = response.data.accessKeyId;
// console.log('ossaccessKeyId值',response.data.accessKeyId);
_self.dataObj.key = response.data.dir + this.getUUID() + '_${filename}';
console.log('图片--->key值',response.data.dir + this.getUUID() + '_${filename}');
_self.dataObj.dir = response.data.dir;
console.log('图片--->dir值',response.data.dir);
_self.dataObj.host = response.data.host;
console.log('图片--->host值',response.data.host);
_self.dataObj.callback = response.data.callback;
resolve(true)
}).catch(err => {
console.log(err)
reject(false)
})
})
},
handlePreview(file) {
console.log('获取图片',file.url);
this.dialogVisible = true;
this.dialogImageUrl = file.url;
},
handleExceed(files, fileList) {
this.$message({
message: '最多只能上传' + this.maxCount + '张图片',
type: 'warning',
duration: 1000
});
},
}
}
</script>
<style>
</style>
上传本地视频至oss
在之前的oss.js文件后添加
export function getUUID () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
}
export function ossUpload (file,editor) {
var that = this;
return new Promise((resolve, reject) => {
policy1().then((response) => {
const formData = new FormData()
//后端返回的key和密匙...
formData.append('OSSAccessKeyId', response.data.accessKeyId)
formData.append('policy', response.data.policy)
formData.append('signature', response.data.signature)
formData.append('key', response.data.dir +getUUID() +'_'+ file.name)
formData.append('callback', response.data.callback)
formData.append('file', file)
formData.append('host',response.data.host)
//回调
axios.post(response.data.host, formData).then((res) => {
const { status } = res
if (status === 200) {
console.log('200',res)
//上传成功后,后台返回图片路径,将图片插入富文本中
editor.cmd.do('insertHTML', `<img src=${res.data.data.filename} alt="">`)
return res.data
} else {
}
}).catch(err => {
console.log(1111,err)
})
}).catch(err => {})
})
}
创建videoUpload.vue组件
效果:
<template>
<div style="display: inline-flex;">
<div class="img-list-item common mb_10" v-for="(item,index) in dialogImageUrl">
<video width="150px" height="150px" style="padding: 0 5px;" controls="controls" :src="item"> 您的浏览器不支持视频播放</video>
<i class="del-img" @click="forkImage(index)"></i>
</div>
<el-upload action="填写oss域名"
:data="dataObj" :show-file-list="false"
:auto-upload="true"
:on-remove="handleRemove"
:on-success="handleUploadSuccess"
:before-upload="beforeUpload"
:limit="maxCount"
accept=".mp4"
:on-exceed="handleExceed"
:on-progress="uploadVideoProcess">
<span class="warp">
<el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;position: relative;top: -15px;">
</el-progress>
<i v-else class="el-icon-plus" :style="{fontSize: '18px',fontWeight:'bold',padding:paddings,position:'relative',top:'60px'}"></i>
</span>
</el-upload>
</div>
</template>
<script>
import {
policy1
} from '@/api/oss'
export default {
props: {
value: Array,
//最大上传图片数量
maxCount: {
type: Number,
default: 5
},
w: {
type: String,
// default:'100px'
},
h: {
type: String,
// default:'100px'
},
paddings: {
type: String,
}
},
data: function() {
return {
videoFlag: false,
videoUploadPercent: 0,
videis: false,
dataObj: {
policy: '',
signature: '',
key: '',
ossaccessKeyId: '',
dir: '',
host: ''
},
dialogVisible: false,
dialogImageUrl: []
}
},
computed: {
fileList() {
let fileList = [];
for (let i = 0; i < this.value.length; i++) {
fileList.push({
url: this.value[i]
});
}
console.log('视频---->', fileList);
console.log('视频22222222222222---->', this.dialogImageUrl);
return fileList;
}
},
methods: {
//删除视频
forkImage(index) {
// console.log('当前索引', index);
this.dialogImageUrl.splice(index, 1);
// console.log('删除后的数组数组', this.dialogImageUrl);
},
getUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
},
emitInput(fileList) {
let value = [];
for (let i = 0; i < fileList.length; i++) {
value.push(fileList[i].url);
}
this.$emit('input', value)
},
handleRemove(file, fileList) {
this.emitInput(fileList)
},
handleUploadSuccess(res, file) {
// console.log("成功后", file)
// console.log('获取图片', res.data);
let url = this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name);
// console.log('路径', url);
this.fileList.push({
name: file.name,
url: url
});
this.dialogVisible = true;
this.dialogImageUrl.push(url);
// console.log("视频地址", this.);
this.emitInput(this.fileList);
this.videoFlag = false;
this.videoUploadPercent = 0;
},
uploadVideoProcess(event, file, fileList) {
this.videoFlag = true;
this.videoUploadPercent = Math.floor(event.percent);
},
beforeUpload(file) {
var fileSize = file.size / 1024 / 1024 < 100;
console.log('视频大小', fileSize);
if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) ==
-1) {
this.$message({
type: 'warning',
message: '请上传正确的视频格式'
});
return false;
}
if (!fileSize) {
this.$message({
type: 'warning',
message: '视频大小不能超过100MB'
});
return false;
}
this.videoFlag = true;
console.log("上传视频值", file);
const _self = this
return new Promise((resolve, reject) => {
policy1().then(response => {
console.log("视频---->获取数据", response.data);
_self.dataObj.policy = response.data.policy;
// console.log('policy值',response.data.policy);
_self.dataObj.signature = response.data.signature;
// console.log('signature值',response.data.signature);
_self.dataObj.ossaccessKeyId = response.data.accessKeyId;
// console.log('ossaccessKeyId值',response.data.accessKeyId);
_self.dataObj.key = response.data.dir + this.getUUID() + '_${filename}';
console.log('视频---->key值', response.data.dir + this.getUUID() + '_${filename}');
_self.dataObj.dir = response.data.dir;
console.log('视频---->dir值', response.data.dir);
_self.dataObj.host = response.data.host;
_self.dataObj.callback = response.data.callback;
resolve(true)
}).catch(err => {
console.log(err)
reject(false)
})
})
},
handlePreview(file) {
// console.log('获取视频', file.url);
this.dialogVisible = true;
this.dialogImageUrl = file.url;
},
handleExceed(files, fileList) {
// console.log("获取上传视频", files, fileList);
this.$message({
message: '最多只能上传' + this.maxCount + '个视频',
type: 'warning',
duration: 1000
});
},
}
}
</script>
<style lang="scss" scoped>
.warp {
display: inline-block;
// padding: 54px 64px;
width: 150px;
height: 151px;
border: 1px dashed #DEE5ED;
}
/deep/.el-upload-list {
display: none;
}
.el-upload-video {
width: 149px;
height: 149px;
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.el-upload-video-i {
font-size: 20px;
font-weight: bold;
padding-top: 43px;
color: #8c939d;
width: 50px;
height: 50px;
line-height: 50px;
text-align: center;
}
//视频
.img-list-item {
position: relative;
margin: auto;
}
// .img-list-item img {
// box-sizing: border-box;
// vertical-align: middle;
// border: 0;
// }
.img-list-item i.del-img {
width: 20px;
height: 20px;
display: inline-block;
background: rgba(0, 0, 0, .6);
background-image: url(../assets/images/close.png);//删除图片
background-size: 18px;
background-repeat: no-repeat;
background-position: 50%;
position: absolute;
top: 0;
right: -1px;
}
</style>
前端小白在此请各位大佬多多指教鸭!!!!记得给我点个赞哟!!!
查看oss各地域名
查看资料:https://blog.csdn.net/weixin_45495667/article/details/111588974?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-3&spm=1001.2101.3001.4242
https://blog.csdn.net/qq_38997036/article/details/107591742
看过很多资料和其它博主写的,有些网址找不到了,有原创若看到,可以私聊我哟!转发请注明原创
更多推荐
所有评论(0)