前一篇说了单张直接上传oss,这篇写多张上传并回显
效果图:
oss:
具体流程见前一篇文章
代码实现:
vue:
<template>
<el-upload class="avatar-uploader"
v-model="Addfrom.url"
action=""
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-change="handleChange"
:file-list="fileList"
:auto-upload="false"
:multiple = true
:before-upload="handleBeforeUpload"
:limit="8">
<div v-for="(item,index) in imageList" :key="index">
<img :src="item" class="avatar" :alt="item">
<p>{{item}}</p>
</div>
<!-- <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size:50px"></i> -->
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
</el-upload>
</template>
<script>
import {client} from './alioss.js'
export default {
data() {
return {
fileList: [],
imageList:[],
Addfrom:{
url:''
}
};
},
methods: {
// 上传文件之前的方法
handleBeforeUpload(file) {
const isJPEG = file.name.split('.')[1] === 'jpeg';
const isJPG = file.name.split('.')[1] === 'jpg';
const isPNG = file.name.split('.')[1] === 'png';
const isWEBP = file.name.split('.')[1] === 'webp';
const isGIF = file.name.split('.')[1] === 'gif';
const isLt500K = file.size / 1024 / 1024 / 1024 / 1024 < 4;
if (!isJPG && !isJPEG && !isPNG && !isWEBP && !isGIF) {
this.$message.error('上传图片只能是 JPEG/JPG/PNG 格式!');
}
if (!isLt500K) {
this.$message.error('单张图片大小不能超过 4mb!');
}
return (isJPEG || isJPG || isPNG || isWEBP || isGIF) && isLt500K;
},
submitUpload() {
this.uploadURL();
},
handleChange(file, fileList){
this.fileList = fileList
console.log(this.fileList);
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
uploadURL() {
for(var i =0;i<this.fileList.length;i++){
let fileName = `${new Date().format('yyyyMMdd/')}` + `${this.fileList[i].raw.uid}` + '.jpg'; //定义唯一的文件名
//定义唯一的文件名,打印出来的uid其实就是时间戳
client().multipartUpload(fileName, this.fileList[i].raw,{
progress: function(percentage, cpt) {
console.log('打印进度',percentage)
}
}).then((res)=>{
console.log('这个是啥',res)
//上传成功之后,回显操作,拼接桶名+域名+文件名
this.imageList.push('https://xxx-oss.oss-cn-beijing.aliyuncs.com/' + fileName)
})
}
},
}
}
</script>
<style scoped lang="scss">
.avatar{
width: 300px;
}
</style>
alioss.js
// var OSS = require('ali-oss');
import OSS from "ali-oss";
export function client(){
var client = new OSS({
endpoint: 'oss-cn-beijing.aliyuncs.com',//填写Bucket所在地域
accessKeyId: 'LTxxxxxxxxxxxxxRAQn',
accessKeySecret: 'NxeyxxxxxxxxxxxxxxGG2',
bucket: 'lst-oss',// 填写Bucket名称。
}) //后端提供数据
return client
}
/**
* 生成随机文件名称
* 规则八位随机字符,加下划线连接时间戳
*/
export const getFileNameUUID = () => {
function rx() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
return `${+new Date()}_${rx()}${rx()}`
}