a-upload自定义上传图片

<template>
  <div>
    <a-upload
      class="upload-btn"
      :action="'#'"
      :show-upload-list="false"
      :customRequest="httpRequest"
      :before-upload="beforeUpload"
    >
      顶部图片
    </a-upload>
  </div>
</template>

<script>
import { uploadArticleFile } from '@/api/edit'
export default {
  components: {},
  data () {
    return {}
  },
  mounted () {
  },
  methods: {
   async httpRequest (file) {
      const formData = new FormData()
      const _this = this
      const reader = new FileReader()
      reader.readAsDataURL(file.file)
      reader.addEventListener('loadend', function (e) {
       const image = new Image()
       image.src = e.target.result
       image.onload = async function () {
         if (image.width !== 1920 || image.height !== 268) {
           _this.$message.error('需要符合要求尺寸的图片!')
           return false
         } else {
           formData.append('file', file.file)
           const { code, data } = await uploadArticleFile(formData)
           if (code === 200) {
             _this.$message.success('上传成功!')
             _this.$emit('uploadImg', data.url)
           } else {
             _this.$message.error('上传失败!请重新上传')
           }
         }
       }
     })
    },
    // 检查图片格式和图片大小, 限制1920尺寸
    async beforeUpload (file) {
      // 图片格式限制为 jpeg、png
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('请选择jpg/png图片')
        return false
      }
      // 图片大小限制为 10M以内
      const isLt10M = file.size / 1024 / 1024 <= 10
      if (!isLt10M) {
        this.$message.error('图片大小不能超过10MB,请重新上传')
        return false
      }
      return isJpgOrPng && isLt10M
    }
  }
}
</script>
<style lang="less" scoped>
.upload-btn {
  width: 100%;
  height: 76px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 2px;
  cursor: pointer;
  margin-bottom: 10px;

  /deep/ .ant-upload {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>

标签