文件立即上传
element + vue
上代码
<el-upload class="upload" action="" drag :show-file-list="false" :auto-upload="false" :on-change="uploadFile"
:file-list="uploadList">
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">请上传10M以内的单张图片!</div>
</el-upload>
<img :src="imgsrc" />
data (){
return {
uploadList: [],
imgsrc: '',
imageType: ['image/jpeg', 'image/jpg', 'image/png'],
}
},
methods: {
validateFile(file){
var index = file.name.lastIndexOf('.');
var fileName = file.name.substr(0, index);
const isLt2M = file.size / 1024 / 1024;
let type = this.imageType.indexOf(file.raw.type);
if (type<0){
message.error('请上传Jpg、Jpeg、Png格式图片!');
return false;
} else if (fileName === '') {
message.error('请上传非空名称的图片!');
return false;
} else if (isLt2M > 10) {
message.error('请上传10M以内的图片!');
return false;
} else if (type>=0 && isLt2M<10){
return true;
}
message.error('未知的异常!')
return false;
},
uploadFile(file) {
let flag = this.validateFile(file);
if (!flag) {
return false;
}
var formData = new FormData();
formData.append('file', file.raw);
formData.append('filename', file.raw.name);
$ajax.upload(formData).then(res=>{
message.info('上传成功');
this.getImgFile(file.raw, res);
})
},
getImgFile: function (file, res) {
let that = this;
var reader = new FileReader();
reader.readAsDataURL(file)
reader.onload = function () {
that.imgsrc = reader.result;
}
},
}
网友评论