Element UI 图片上传

Element UI 图片上传
Element UI 图片上传

<div>
  <!-- <input
    v-model="postModel.title_img"
    type="text"
    class="allInput"
  /> -->
  <el-upload
    class="images-uploader"
    action="#"
    :http-request="handelImageRequest"
    :show-file-list="false"
    :before-upload="beforeImagesUpload"
    :auto-upload="true"
  >
    <img
      v-if="postModel.title_img"
      :src="postModel.title_img"
      class="images"
    />
    <i v-else class="el-icon-plus images-uploader-icon"></i>
  </el-upload>
</div>
beforeImagesUpload(file) {
  const ext = file.type.split('/')[1];
  const isImg = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1;
  const isLt2M = file.size / 1024 / 1024 < 1;

  if (!isImg) {
    this.$message.error("请上传正确的图片文件!");
  }
  if (!isLt2M) {
    this.$message.error("图片大小不能超过1MB!");
  }
  return isImg && isLt2M;
},
handelImageRequest(param) {
  const formData = new FormData()
  formData.append('file', param.file)
  let config = {
      headers:{"Content-Type":"multipart/form-data"}
  };
  let that = this;
  this.$axios.post("/Upload/getImgUrl", formData , config ).then((p) => {
      // console.log(p); // 直接返回图片地址
      that.postModel.title_img = p;
  });      
}
<style scoped>
.images-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.images-uploader .el-upload:hover {
  border-color: #409eff;
}
.images-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border:1px dashed #8c939d;
}
.images {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
上一篇:Vue实现阿里云oss文件上传(服务端签名后直传)


下一篇:使用 FormData 进行 Ajax 请求并上传文件