vue3使用ElementPlus upload上傳檔案的兩種方式

發表於2024-02-23

1. 不使用action

image.png

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) }

相關文章