关于vue3:vue3使用ElementPlus-upload上传文件的两种方式

109次阅读

共计 2207 个字符,预计需要花费 6 分钟才能阅读完成。

1. 不应用 action

a: html 局部(上传单个文件)

<el-upload
  class="avatar-uploader"
  action="#"
  :limit="1"
  :show-file-list="false"
  :http-request="handleUpload"
  :before-upload="handleChange"
  accept=".png,.jpe,.jpeg"
  ref="uploadBanner"
>
  <img v-if="formData.appLogo" :src="formData.appLogo" class="avatar" />
  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  <el-icon
    v-if="formData.appLogo"
    class="logoDelete"
    @click.stop="clearUploadImg"
    ><CircleCloseFilled
  /></el-icon>
</el-upload>

b: js 局部

// 上传
const handleChange = (rawFile) => {if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {ElMessage.error("只能上传 jpeg/jpg/png 图片");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 1) {ElMessage.error("上传图片最大不超过 1MB!");
    return false;
  }
  return true;
};
const handleUpload = async (file) => {let fd = new FormData();
  fd.append("file", file.file);
    // 这里是申请上传接口
    let result = await uploadFile(fd);
    if (result.code == 200) {
      // 后盾只返回文件名称,须要拼接
      formData.value.appLogo =
        import.meta.env.VITE_APP_HOSTURL +
        import.meta.env.VITE_APP_BASEURL +
        "file/previewFile/" +
        result.data;
      // 去掉 form 表单验证的 *
      // formRef.value.clearValidate(['appLogo'])
      // 上传胜利清空文件
      uploadBanner.value.handleRemove(file);
    } else {
      formData.value.appLogo = "";
      ElMessage.error(result.message);
      uploadBanner.value.handleRemove(file);
    }

};
const clearUploadImg = (file) => {
  formData.value.appLogo = "";
  uploadBanner.value.clearFiles();};

2. 应用 action 上传

a. html 局部(上传多个文件)

<el-upload action="uploadUrl" list-type="picture-card" v-model:file-list="formData.fileList" :limit="9" accept="image/*" :before-upload="beforeUpload" :on-success="handleSuccess">
  <el-icon>
    <Plus />
  </el-icon>
  <template #file="{file}">
    <div>
      <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
      <span class="el-upload-list__item-actions">
        <span class="el-upload-list__item-delete" @click="handleRemove(file)">
          <el-icon>
            <Delete />
          </el-icon>
        </span>
      </span>
    </div>
  </template>
</el-upload>

b. js 局部

const uploadUrl = import.meta.env.VITE_APP_HOSTURL + "/imgUpload/upload";

const handleRemove = (file) => {for (let i = 0; i < formData.fileList.length; i++) {let item = formData.fileList[i]
    if (item.uid === file.uid) {formData.fileList.splice(i, 1)
      return true
    }
  }
  console.log(file)
}
const beforeUpload = (file) => {
  const isLtSize = file.size / 1024 / 1024 < 5;
  if (!isLtSize) {ElMessage.error("上传图片大小不能超过 5MB!");
    return false;
  }
  return true;
}
const handleSuccess = (file) => {console.log(file) }

正文完
 0