使用vuejs预览多张图片

时间:2019-07-23 03:42:53

标签: javascript vue.js vuejs2

这是使用vue js上传和预览多个文件的最佳方法

     createPost() {
      const formData = new FormData();
      _.forEach(this.uploadFiles, file => {
        if (this.invalidMessage(file) === "") {
          formData.append("files",file)
        }
      });
      this.$store.dispatch("feeds/createdfeed", {
        body: this.form.body,
        avatar:formData
      });
      this.$message.success('Loading finished', 5.5)
      this.$store.dispatch("profile/getUserFeeds", {
        id: this.$route.params.id,
        page: 1
      });
    },
    selectFile() {
      const files = this.$refs.files.files;
      this.uploadFiles = [...this.files, ...files]
      this.files = [
        ...this.files,
        ..._.map(files, file =>({
          name:file.name,
          size: file.size,
          type: file.type,
          url: URL.createObjectURL(file),
          invalidMessage: this.validate(file)
        }))
      ]
    },
    validate(file){
      const MAX_SIZE = 200000
      const allowedTypes = ['image/jpeg','image/png','image/gif']
      if (file.size > MAX_SIZE) {
        this.$message.error(`Max size ${MAX_SIZE/1000}kb. Please try again.`,5.5);
      }
      if (!allowedTypes.includes(file.type)) {
        this.$message.error(`Not an image.Please try again.`);
      }
    }
  }

我遍历了多个文件,以便在上传之前预览文件。但是现在,这仍然行不通。

0 个答案:

没有答案