Vant Uploader upload picture function

van-uploader reference documentation

  1. Limit the number of uploads The
    number of uploaded files can be limited through the max-count attribute. After the number of uploads reaches the limit, the upload area will be automatically hidden.
  2. Limit upload size
    The size of the uploaded file can be limited through the max-size attribute. Files exceeding the size will be automatically filtered, and the file information can be obtained through the oversize event.
  3. Verify and process the file before uploading Through the before-read function, you can perform verification and processing before uploading, and support returning Promise to customize the file object. For example, compress pictures: use compressorjs to compress pictures, optimize functions, and compress pictures in all formats.
  4. After the file is uploaded, the data will be obtained. After the file is uploaded, the after-read callback function will be triggered to obtain the corresponding file object.
  5. For more details, please refer to the vant official documentation
<template>
  <div>
    <van-uploader
      v-model="fileList"
      :max-count="1"
      :max-size="2048 * 1024"
      :after-read="OnAfterRead"
      :before-read="onBeforeRead"
      @oversize="onOversize"
      @delete="onDelete"
    />
  </div>
</template>

<script>
import Compressor from "compressorjs";
export default {
    
    
  data() {
    
    
    return {
    
    
      fileList: [],
      IMG_LIST: "", //图片路径

     
    };
  },
  methods: {
    
    
    OnAfterRead(result) {
    
    
      let newImage = new Image();
      // 这里将src传入需要获取信息的图片地址或base64
      newImage.src = result.content;

      newImage.onload = () => {
    
    
        // 输出图片信息 比如可以获取图片宽高
        console.log("图片宽", newImage.width);
        console.log("图片高", newImage.height);
        this.fileList[0].url = result.content;
        // 点击上传图片的结果(base64的图片字符串)IMG_LIST
        this.IMG_LIST = this.fileList[0].url;
        // 控制台打印
        console.log(" this.IMG_LIST ", this.IMG_LIST);
      };
    },
    //上传图片压缩,需要安装依赖: npm i compressorjs,并引入(import) 图片0.6倍压缩
    onBeforeRead(file) {
    
    
      return new Promise((resolve) => {
    
    
        new Compressor(file, {
    
    
          quality: 0.6,
          success: resolve,
          error(err) {
    
    
            console.log('图片压缩失败---->>>>>',err.message);
          },
        });
      });
    },
    //图片大小超过2M提示
    onOversize(file) {
    
    
      this.$toast("图片大小不能超过 2M");
    },
    //点击移除图片
    onDelete() {
    
    
      this.fileList = [];
    },
  },
};
</script>

<style>
</style>

Guess you like

Origin blog.csdn.net/CSSAJBQ_/article/details/128012890