Vue + Element UI 在上传文件前预览 PDF

Vue + Element UI with preview PDF before upload file

我是用vue和element UI实现上传文件功能,也是用pdfvuer节点模块。 在这种情况下,文件最终会上传到Amazon S3。

我想在用户点击确认按钮之前预览文件。 参考图片:upload

目前我使用blob和createObjectUrl方法实现预览PNG和JPG类型的文件。但不适用于 PDF 类型 参考图片:upload and preview png

这是我上传对话框的代码:

HTML :

      <span class="pt-0">
        <p class="text-center mt-0">Please selecct file which you want to import</p>
        <el-upload
          accept="image/png, image/jpeg, application/pdf"
          class="avatar-uploader"
          :show-file-list="true"
          :before-upload="beforeAvatarUpload"
          action=""
        >
          <i class="fas fa-cloud-upload-alt fa-2x my-8" v-if="objectURL == ''"></i>


          <img :src="objectURL" width="100%" />
          <pdf :src="imageUrl.webkitRelativePath" />


          <div class="el-upload__text" v-if="objectURL == ''">Click here to execute</div>
          <div class="el-upload__tip" slot="tip">
            You can just upload PDF/PNG/JPG file only
          </div>
        </el-upload>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogUploadFile = false">Cancel</el-button>
        <el-button type="danger" @click="handleUploadFile">Confirm</el-button>
      </span>
    </el-dialog>

JS :

data(){ retrun ... }
methods:{
   beforeAvatarUpload(file) {
      this.objectURL = window.URL.createObjectURL(new Blob([file]));
      this.imageUrl = window.URL.createObjectURL(new Blob([file]));
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isPDF = file.type === "application/pdf";
      const isLt2M = file.size / 1024 / 1024 < 20;
      switch (file.type) {
        case "image/png":
          this.fileType = 1;
          break;
        case "image/jpeg":
          this.fileType = 2;
          break;
        case "application/pdf":
          this.fileType = 3;
          break;
        default:
          break;
      }
      return isJPG && isPNG && isPDF && isLt2M;
    },
}

有人可以帮我解决这个问题吗? 要么给我另一种重写代码的方法。

如果需要有关我的代码的更多详细信息,请告诉我。

尝试将 && 更改为 ||

return isJPG || isPNG || isPDF || isLt2M;

或者我应该说,

return ( isJPG || isPNG || isPDF ) && isLt2M;

已更新。我终于找到了我的问题的解决方案。 我只是使用 <embed> 标签来达到预览功能。

这是我的代码:

<input @change="handleChange" />

// preview area
<embed
    v-if="embedSrc"
    type="video/webm"
    :src="embedSrc"
    width="100%"
    style="max-height: 50rem; min-height: 20rem"
/>

...
data:{
  return {
    embedSrc: ''
  }
}
...
methods:{
   handleChange(){
      this.embedSrc = URL.createObjectURL(event.target.files[0]);
   }
}

请注意src前加:,否则无法正确获取动态src