1.简略的布局(样式以去除),左边是图片浏览,右边是一个input和一个span,当然span是可以自己去设计的,input是隐藏的通过点击外层div来触发它的onclick事件
<!--这里展示大图-->
<div class="full_image" v-if="full_image">
<img :src="full_image" style="border-radius:3px">
<span style="position:absolute;right:10px;top:8px;font-size:16px;font-weight:400;cursor:pointer;user-select:none" @click="full_image=''">X</span>
</div>
<!--上传图片-->
<div >
<!--缩略图-->
<div v-if="images">
<img :src="image.url" v-for="(image,index) in images" :key="index" @click="showImage" :data-url="image.url+''" style="cursor:pointer;">
</div>
<!--上传图片-->
<div @click="uploadImage">
<div style="width:80px;height:80px">
<input type="file" ref="image_input" accept=".png,.jpg,.jpeg" @change="imageSelect" hidden>
<span>+</span><span>上传图片</span><span>({{images.length}}/6)</span>
</div>
</div>
</div>
<button @click="submit">提交</button>
2.images是一个数组存放已选择的图片文件base64编码,full_image点击缩略图时将base64放进去以显示大图,files用户选择的文件都放进去,image_urls是上传后返回的url;注意base64编码是为了不上传图片到服务器也能在页面预览
import { ossTempAuth } from '@/api/oss'
import OSS from 'ali-oss';
data() {
return {
images: [],
full_image: '',
files: [],
image_urls: [],
};
},
3.这里是事件方法
uploadImage() {
this.$refs.image_input.dispatchEvent(new MouseEvent('click'));
},
showImage(event) {
this.full_image = event.target.dataset.url;
},
imageSelect(event) {
let file = event.target.files[0];
for (let i = 0; i < this.images.length; i++)
if (file.name == this.images[i].name) return;
let ofReader = new FileReader();
ofReader.readAsDataURL(file);
ofReader.onload = evo => {
let base64 = evo.target.result;
this.$set(this.images, this.images.length, { name: file.name, url: base64 });
this.files.push(file);
}
},
4.上传
submit(){
this.uploadFiles();
},
async uploadFiles() {
var self = this;
var files = this.files;
var video = this.video_file;
let authConfig = await ossTempAuth();
let back = authConfig.data;
const client = await new OSS({
region: back.region,
accessKeyId: back.AccessKeyId,
accessKeySecret: back.AccessKeySecret,
bucket: back.bucket,
stsToken: back.SecurityToken,
});
async function uploadImage() {
try {
for (let i = 0; i < files.length; i++) {
let name = files[i].name;
let index = name.lastIndexOf(".");
let ext = name.substr(index + 1);
const result = await client.put(
'hummingbird_v2/returns/pic/' + new Date().getTime() + self.uuid(10, 16) + i + '.' + ext,
files[i],
{
'Content-Encoding': 'UTF-8',
'Expires': 'Wed, 08 Jul 2030 16:57:01 GMT',
}
);
self.image_urls[i] = result.url;
}
} catch (e) {
this.model_upload = false;
console.log("上传图片失败", e);
}
}
if (files.length > 0) uploadImage();
},
|