vue上传单张图片
效果如下,图片可点击替换:
<el-form-item label=" " style="margin-left:4px;height:70px"> <div class="el-input el-input-group el-input-group--prepend addprepend" style="height:100%"> <div class="el-input-group__prepend addPrependText-medium" tabindex="-1" style="height:100%"> <span>海报图片</span> </div> <el-upload :action="uploadImg" :on-preview="handlePreview" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :on-remove="handleRemove"> <div style="border: 1px solid #ccc;padding: 10px;height:100%;"> <div v-if="!form.img" style="width:200px"><i class="el-icon-plus" style="margin-top:4%"/></div> <img v-else :src="form.img" style="width:200px"> </div> </el-upload> </div> <span style="color:red;font-size:12px">推荐尺寸750*750</span> </el-form-item>
data() { return { form: { name: '', category: '', img: '' }, fileList: [], uploadImg: process.env.BASE_API + '/management/fileupload/qiniu/img' }
iniData() { if (!this.selectId) { //添加初始化 this.$axios .get('base/posters/create') .then(res => { this.form = res.content.poster this.types = res.content.categoryList }) .catch(res => {}) } else { //编辑初始化 this.$axios .get('base/posters/' + this.selectId + '/update') .then(res => { this.types = res.content.categoryList res.content.poster.category = res.content.poster.categoryId this.form = res.content.poster this.fileList = [{ name: '', url: this.form.img }] }) .catch(res => {}) }
beforeAvatarUpload(file) { console.log(file) const isJPG = file.type console.log(file.type) const isLt2M = file.size / 1024 / 1024 < 2 if ( isJPG != 'image/jpg' && isJPG != 'image/png' && isJPG != 'image/jpeg' && isJPG != 'image/gif' ) { this.$message.error('只能上传.jpg .png .jpeg .gif类型的文件!') } if (!isLt2M) { this.$message.error('上传图片大小不能超过 2MB!') } return isJPG && isLt2M }, handlePreview(file) { console.log(file) }, handleRemove(file) { console.log(file) }, handleAvatarSuccess(res, file) { console.log('=======================', res) this.form.img = res.content.accessUrl this.img = [{ name: '海报图片.png', url: res.content.accessUrl }] },