Vue 使用antd上传图片,代码整合如下

770 阅读1分钟
<template>
    <div class="clearfix">
        <a-upload
          name="headfile"
          action="http://vueshop.glbuys.com/api/user/myinfo/formdatahead?token=1ec949a15fb709370f"
          list-type="picture-card"
          :file-list="fileList"
          @preview="handlePreview"
          @change="handleChange"
        >
          <div v-if="fileList.length < 1">
            <a-icon type="plus" />
            <div class="ant-upload-text">
              上传
            </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>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
    };
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ file, fileList }) {
      const isJpgOrPng = file.type === "image/jpeg";
      if (!isJpgOrPng) {
        this.$message.error("文件格式不正确!");
        return isJpgOrPng;
      }

      const isLt50K = file.size <= 50 * 1024;
      if (!isLt50K) {
        this.$message.error("文件大小不得超过50k!");
        return isLt50K;
      }

      if (isJpgOrPng && isLt50K) {
        this.fileList = fileList;

        // 如果上传状态为uploading
        if (file.status === "uploading") {
          return;
        }
        // 如果上传状态为done
        if (file.status === "done") {
          let url =
            "http://vueshop.glbuys.com/userfiles/head/" +
            file.response.data.msbox;
          this.url = url;
        }
      }
    },
  },
};
</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>