element文件上传

 
            
            
            
将文件拖到此处,或点击上传

方法:

 beforeUpload(file) {
      // 获取上传文件大小
      const imgSize = Number(file.size / 1024 / 1024);
      if (imgSize > 20) {
        this.$message({
          message: '文件大小不能超过20MB,请重新上传。',
          type: 'warning',
        });
        return false;
      }
      return true;
    },

    async uploadFile() {
      let annexList = [];
      if (this.fileList.length <= 0) {
        return;
      }
      const formData = new FormData();
      // fileList 在data中定义的数组,把所有文件放到formData中,xxx未后台定义字段名
      this.fileList.forEach(f => {
        formData.append('xxxx', f.raw);
      });
      await upload(formData)
        .then(res => {
          let list = res?.data || [];
          annexList = list.map(res => {
            return res.url;
          });
        })
        .catch(e => {
          this.$message.warning('文件上传失败,请重试');
          this.fileList = [];
        });
      return annexList;
    },
    onchange(file) {
      this.fileList.push(file);
    },
    async handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    async handleSubmit() {
      this.form.annexList = await this.uploadFile();
      this.$refs.form.validate(valid => {
        if (!valid) {
          return;
        }
        //xxx为整个表单的值
        xxx(this.form).then(res => {
          if (res?.code == 200) {
            this.$message.success('发布成功');
            this.$router.go(-1);
          }
        });
      });
    },

你可能感兴趣的:(前端,vue.js,javascript,elementui)