这里是以普通input图片上传
具体还可以参考MDN
<template>
<input type="file" accept="image/*" @change="upload"/>
<img :src="this.imageUrl" :alt="this.fileName" />
</template>
data () {
return {
imageUrl: "",//图片链接
imgWidth: "",//图片宽
imgHeight: "",//图片高
fileName: "",//图片名字
}
}
methods: {
upload(e) {
const _this = this;
const file = e.target.files[0];//方便下文直接使用file代替e.target.files[0]
const reader = new FileReader();
//图片读取
reader.onload = function() {
const img = new Image();
const url = this.result;
img.onload = function() {
_this.imageUrl = url;//图片链接
_this.imgWidth = this.width;//图片宽
_this.imgHeight = this.height;//图片高
}
img.onerror = function() {
//todo图片加载失败的处理函数
//例如:this.$message.error('图片加载失败,请重新上传');
}
img.src = url;
}
reader.onerror = function () {
//todo图片上传失败的处理函数
//例如:this.$message.error('图片上传失败,请重新上传');
};
reader.readAsDataURL(file);
this.fileName = file.name;
}
}
Element上传插件也是大同小异(参考网上方法)
<el-upload
drag
:action="/upload"
accept="image/png, image/jpeg, image/gif, image/jpg"
:headers="headers"
:on-success ="successUploads"
:before-upload ="uploadyanzheng"
name="image"
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
methods:{
uploadyanzheng(file) {
let _this = this
// 普通的判断可以用return false
// 获取文件尺寸,判断尺寸在不在规定范围之内
return new Promise(function(resolve, reject) {
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function(theFile) {
let image = new Image()
image.src = theFile.target.result
image.onload = function() {
let csize = `${this.width}*${this.height}`
if (!_this.creativeSize.includes(csize)) {//this.creativeSize是可以上传的尺寸列表数组
_this.$message.error(`${file.name}尺寸不对,请重新上传!`)
reject('图片尺寸不对')
} else {
file.width = this.width
file.height = this.height
resolve(file)
}
}
}
})
},
}