上传图片
上传图片
<el-form ref="filters" :model="filters" label-width="120px"> <el-form-item label="上传图片:" prop="imgPath"> <el-upload class="avatar-uploader" :action="uploadActionUrl" // 要调的接口 :show-file-list="false" :headers="uploadHeaders" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :data="{ token: token, op: 'upLoadAudioRecordFile', data: '{}' }" > <img v-if="filters.imgPath" // 后台反的字段 进行绑定 :src="filters.imgPath" class="avatar" /> <i v-else class="el-icon-plus avatar-uploader-icon"></i> <div slot="tip" class="el-upload__tip"> 建议尺寸:355*118;建议大小:100K;建议格式:gif | png </div> </el-upload> </el-form-item> <el-form>
js文件 export const uploadActionUrl = () => process.env.VUE_APP_BASEURL + '接口地址' 引入 import { uploadActionUrl } from "@/apis/upload"; computed: { uploadActionUrl, // 对应页面中 :action uploadHeaders() { const token = window.localStorage.getItem("token"); return { "X-Token": token }; }, }, methods:{ handleAvatarSuccess(resp, file) { // 可以打印一下resp和file const [imgPath] = resp.data; this.filters.imgPath = imgPath; // 对应页面绑定的filters }, beforeAvatarUpload(file) { const isIMAGE = file.type === "image/gif" || "image/png"; // 图片类型 const isLt2M = file.size / 1024 / 1024 < 100; // 限制小于100K // 图片大小 if (!isIMAGE) { this.$message.error("上传文件只能是图片格式!"); } if (!isLt2M) { this.$message.error("上传图片大小不能超过 100K!"); } return isIMAGE && isLt2M; }, }
<style scoped> .avatar-uploader .el-upload { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; } .avatar-uploader .el-upload:hover { border-color: #409eff; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; width: 150px; height: 100px; line-height: 100px; text-align: center; } .avatar { width: 150px; height: 100px; display: block; } </style>