vue实现 Element-UI 的 el-upload 图片文件上传 demo

1.上传效果

请添加图片描述

2.vue实现代码(比较简单的demo,直接看)

 <template>
  <div class="content">
    <el-upload
      class="avatar-uploader"
      action=""
      :http-request="handleRequest"
      :show-file-list="false"
      :disabled="loading"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="basePath + imageUrl" class="avatar" />
      <span
        v-if="imageUrl"
        @click.stop="imageUrl = ''"
        class="el-icon-error del"
      ></span>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import {
     
      staticResource, addEditEquipment } from '@/api'
export default {
     
     
  data() {
     
     
    return {
     
     
      loading: false,
      imageUrl: '',
      basePath: ''
    }
  },
  // 获取文件上传基地址
  async mounted() {
     
     
    this.basePath = await staticResource.uploadBasePathByDevice()
  },
  methods: {
     
     
    // 文件上传格式,大小校验
    beforeAvatarUpload(file) {
     
     
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
     
     
        this.$message.error('上传图标只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
     
     
        this.$message.error(this.$t('上传图标大小不能超过 2MB'))
      }
      return isJPG && isLt2M
    },
    // 文件上传
    handleRequest(params) {
     
     
      try {
     
     
        this.loading = true
        let file = params.file
        const data = new FormData()
        data.append('file', file)
        data.append('type', 4)
        // 文件上传接口
        addEditEquipment.upload(data).then((res) => {
     
     
          this.loading = false
          this.imageUrl = res.fileUrl
        })
      } catch (error) {
     
     
        console.log('文件上传失败' + JSON.stringify(error))
      } finally {
     
     
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
     
     
  width: 100px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.avatar-uploader {
     
     
  border-radius: 5px;
  border: 1px dashed #d9d9d9;
  cursor: pointer;
  position: relative;
}
.avatar-uploader-icon {
     
     
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
img {
     
     
  width: 100%;
}
.del {
     
     
  color: red;
  position: absolute;
  top: 5px;
  right: 5px;
  z-index: 1;
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_36410795/article/details/123580787