AntdV 单个图片上传 自定义上传

文件架构
1、放在components下image-uploader
在这里插入图片描述
2、main.js 引入
在这里插入图片描述

前端部分:
1)index.vue

<template>
  <div class="clearfix">
    <a-upload
      name="file"
      list-type="picture-card"
      :file-list="fileList"
      @preview="handlePreview"
      @change="handleChange"
      :before-upload="beforeUpload"
      :customRequest="uploadImage"
    >
      <div v-if="fileList.length === 0">
        <a-icon type="plus" />
        <div class="ant-upload-text" >
          Upload
        </div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
import { uploadImage } from '../../api/image'

export default {
  data () {
    return {
      previewVisible: false,
      previewImage: '',
      imageUrl: '',
      fileList: []
    }
  },
  methods: {
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      this.previewImage = file.url
      this.previewVisible = true
    },
    handleChange ({ fileList }) {
      this.fileList = fileList
      if (this.fileList.length === 0) {
        this.$emit('success', '')
      }
    },
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isJpgOrPng) {
        this.$message.error('只能上传png、jpg、jpeg格式的图片!')
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('图片尺寸不能超过 10MB!')
      }
      return isJpgOrPng && isLt2M
    },
    uploadImage (file) {
      const formData = new FormData()
      formData.append('file', file.file)
      uploadImage(formData).then(res => {
        if (res.code === 0) {
          this.imageUrl = process.env.VUE_APP_IMAGE_URL + res.data
          this.$emit('success', res.data)
          this.fileList = [{
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: this.imageUrl
          }]
        }
      }).catch(() => {
      })
    }
  }
}
</script>
<style>
  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  1. 引入的的 uploadImage

在这里插入图片描述
这里是已经封装好的 request,如果嫌麻烦,可以直接写个ajax请求,将资源发送给后台。

3、组件调用

在这里插入图片描述

后台部分:
在这里插入图片描述
效果:

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值