2

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

张旭超
1.4k 声望222 粉丝

精通 html+div+css jquery, vue, angularjs, angular2, angular4, ionic, ionic2