vue-cli 手写图片上传功能 阿里云OSS
<template>
<div style="width: 100%;display: flex;justify-content: center;">
<label class="img" for="upload" :class="{ uploading:showUp }">选择图片上传</label>
<input type="file" multiple id="upload"
style="display: none;" accept="image/*"
@change="onChagne" ref="file"
disabled="showUp"
>
<p class="tip">提示: 一次可以选择多张图片, 最多不超过9张 (单张图片大小 < 1M)</p>
<ul class="img-container">
<li v-for="(item, index) in imgList" :key="index" :style="{ background: `url(${item}) no-repeat center/contain` }"></li>
</ul>
</div>
<!-- html 触发文件上传的弹框multiple代表可以多选 label 标签for指向某个文件
点击时相当于点击某个文件
accept接受的意思 image/* 表示接受所有图片格式的文件
vue 获取当前元素的内容 ref属性 在方法里调用this.$refs.+定义好的文件名称
-->
</template>
<script>
// import OSS from 'ali-oss'
export default {
methods: {
data() {
return {
// client: new OSS({
// region: 'oss-cn-beijing', // 地区, 地域
// bucket: 'imooc-hky', // 名称
// accessKeyId: '', // 唯一标识 表示阿里云的哪一个用户
// accessKeySecret: ''
// }),
imgList: [], // 存放上传完成图片
showUp: false
}
},
onChagne() {
// const file = this.$refs.file
const newFiles = this.$refs?.file?.files
console.log(newFiles)
// 可选链
if (newFiles.length > 9) {
alert('最多一次可以选择9张图片')
return false
}
const files = []
for (const file of newFiles) {
const size = file.size / 1024 / 1024 // 把单位转换成M
if (size > 1) {
alert('请选择小于1M的图片')
return false
}
files.push(file)
}
console.log(files)
this.uploadFiles2(files)
},
// 上传到阿里云的OSS
uploadFiles(files) {
this.uploading = true
const uploadResult = []
for (const file of files) {
uploadResult.push(new Promise((resolve, reject) => {
this.client.put(`${Math.random()}-${file.name}`, file).then(res => {
// console.log(res)
// this.imgList = [...this.imgList, res.url] // 拓展运算符 但是有一个缺点 不能按点击的顺序排列照片
resolve(res.url)
}) // 上传到阿里云 第一个参数是名称 名称不能重复 否则会被覆盖 第二个参数是文件本身
}).catch(err => {
console.log(err)
// reject(err)
}))
}
Promise.allSettled(uploadResult).then(res => {
console.log(res)
const imgs = []
for (const item of res) {
if (item.status === 'fulfilled') {
imgs.push(item.value)
}
}
this.imgList = imgs
this.uploading = false
}).catch(err => {
console.log(err)
})
},
async uploadFiles2(files) { // async await 方法来上传更加的优雅
this.uploading = true
const imgs = []
for (const file of files) {
const result = await this.client.put(`${Math.random()}-${file.name}`, file)
imgs.push(result.url)
}
this.imgList = imgs
this.uploading = false
}
}
}
</script>
<style scoped>
/* 表示样式在当前作用域起作用 */
.img {
display: block;
width: 150px;
height: 50px;
text-align: center;
line-height: 50px;
background-color: #42B983;
color: white;
border-radius: 5px;
cursor: pointer;
}
.tip {
color: red;
margin-left: 50px;
}
.uploading{
background-color: #CCCCCC;
}
.img-container > li{
list-style: none;
width: 150px;
height: 100px;
float: left;
margin: 0 30px 30px 0;
border: 1px solid #ccc;
}
</style>

浙公网安备 33010602011771号