华域联盟 JAVA Vant Uploader实现上传一张或多张图片组件

Vant Uploader实现上传一张或多张图片组件

本文实例为大家分享了Vant Uploader实现上传一张或多张图片组件,供大家参考,具体内容如下

html部分

<template>
  <div class="contWrap">
    <van-uploader
      v-model="fileList"
      :multiple="true"
      :before-read="beforeRead"
      :after-read="afterRead"
      :before-delete="delUploadImg"
      upload-icon="plus"
    >
    <!-- 注:这里是自定义上传样式 -->
      <!-- <p>
        <van-icon
          name="plus"
          color="#07c160"
          size=".5rem"
        />
        上传照片
      </p> -->
    </van-uploader>
  </div>
</template>

js部分

<script>
import axios from "axios";
export default {
  name: "uploadImages",
  data() {
    return {
      fileList: [],
      uploadUrl: "/api/upload/fileUpload",
      headers: {
        token: this.$store.state.account.token,
      },
    };
  },

  methods: {
    // 返回布尔值
    beforeRead(file) {
      if (file instanceof Array) {
        //判断是否是数组
        file.forEach((v) => {
          this.checkFile(v);
        });
      } else {
        this.checkFile(file);
      }
      return true;
    },
    //图片类型检查
    checkFile(file) {
      const format = ["jpg", "png", "jpeg"];
      const index = file.name.lastIndexOf(".");
      const finalName = file.name.substr(index + 1);
      if (!format.includes(finalName.toLowerCase())) {
        Toast("请上传" + format.join(",") + "格式图片");
        return false;
      }
    },
    afterRead(file) {
    // 此时可以自行将文件上传至服务器
      if (file instanceof Array) {
        file.map((v) => {
          v.status = "uploading";
          v.message = "上传中...";
          this.uploadImg(v);
        });
      } else {
        file.status = "uploading";
        file.message = "上传中...";
        this.uploadImg(file);
      }
    },
    //上传
    uploadImg(file) {
      const formData = new FormData();
      formData.append("file", file.file);
      axios
        .post(this.uploadUrl, formData, {
          headers: this.headers,
        })
        .then((res) => {
          if (res.data) {
            if (file instanceof Array) {
              //判断是否是数组
              file.map((v, i) => {
                v.status = "success";
                v.message = "";
                v.url = res.data[i];
              });
            } else {
              file.status = "success";
              file.message = "";
              file.url = res.data.uploadUrl;
            }
          }
        })
        .catch((err) => {
          this.$notify({
            type: "warning",
            message: "上传失败",
          });
        });
    },
    //删除
    delUploadImg(item) {
      this.fileList = this.fileList.filter((v) => v.url != item.url);
    }
  },
};
</script> 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Vant Uploader实现上传一张或多张图片组件

转载请保留出处和原文链接:https://www.cnhackhy.com/81629.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部