原生js实现图片/PDF导入(PDF导入需后端处理)

21 篇文章 0 订阅
6 篇文章 0 订阅
  public onUpload(): void {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept =
      'image/gif,image/jpeg,image/jpg,image/png,image/svg,.svg,application/pdf';
    let file: File = null;
    const readPDFPromise = new Promise<File>((resolve, reject) => {
      fileInput.addEventListener('change', (_) => {
        file = fileInput.files[0];
        const fileSize = Math.floor(file.size / (1024 * 1024));
        if (fileSize > this._limitSize) {
          this.baseContext.srvMessage.info(
            `文件太大,目前图片仅支持小于${this._limitSize}M的图片文件!`,
            5000
          );
          return;
        }

        if (file.type !== 'application/pdf') {
          const reader = new FileReader();

          reader.onload = (e) => {
            const dataURL = reader.result;
            const img = new Image();
            img.onload = () => {
              this.createTextureAsset(
                file,
                this._width || img.width,
                this._height || img.height
              );
            };
            img.src = <string>dataURL;
          };
          reader.readAsDataURL(file);
        }
        resolve(file);
      });
    });

    fileInput.click();

    // importPDF
    let imgUrl: string = '';
    readPDFPromise
      .then((file) => {
        if (file.type === 'application/pdf') {
          const formData = new FormData();
          formData.append('file', file);
          formData.append('id', '');
          formData.append('type', file.type);
          formData.append('burnafterreading', 'true');

          formData.append('reason', 'udesign::upload_drawing_pdf');
          formData.append('refer', this.baseContext.doc.id);

          const params: any = {
            formData: formData,
            // we need the resultant image in the future
            // let's store in storage
            burnafterreading: false,

            // you can choose svg or png
            output: this.pdfTrans2PNG ? 'png' : 'svg',
          };
          //后端处理pdf=>image.png
          return new Promise((resolve, reject) => {
            this.showLoading = true;
            this.baseContext.srvCloud.callFnc(
              'processPDF',
              params,
              (err, res) => {
                if (!err && res) {
                  resolve(res);
                } else {
                  reject(new Error('process pdf error'));
                }
              }
            );
          });
        } else {
          return new Promise(() => { }); //终止Promise
        }
      })
      .then((res: any) => {
        this.showLoading = true;
        imgUrl = res.path;

        return this._impl.loadImage(imgUrl);
        // return new Promise((resolve, reject) => {
        //   resolve({
        //     texture: null,
        //     pathResolve: this.baseContext.cloudService.callUtilSyncMethod(
        //       'resolveStoragePath',
        //       res.path
        //     )
        //   });
        // });
      })
      .then(({ texture, pathResolve }) => {
        return pathResolve;
      })
      .then((path) => {
        // return this._impl.getImgToBase64(path);
        return path;
      })
      .then((dataUrl) => {
        this.getImageFileFromUrl(dataUrl, file.name + '.png', file => {
          const reader = new FileReader();
          reader.onload = (e) => {
            const dataURL = reader.result;
            const img = new Image();
            img.onload = () => {
              this.createTextureAsset(
                file,
                img.width,
                img.height
              );
            };
            img.src = <string>dataURL;
          };
          reader.readAsDataURL(file);
        });
      })
      .catch((err) => {
        console.error(err);
        this.baseContext.srvMessage.info('PDF文件导入失败', 5000);
        this.showLoading = false;
      });
  };


  getImageFileFromUrl(url, imageName, callback) {
    // imageName一定要带上后缀
    var blob = null;
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.setRequestHeader('Accept', 'image/png');
    xhr.responseType = "blob";
    xhr.onload = () => {
      //console.log('111')
      if (xhr.status == 200) {
        blob = xhr.response;
        let imgFile = new File([blob], imageName, { type: 'image/png' });
        //console.log(imgFile)
        callback.call(this, imgFile);
      }
    };
    xhr.send();
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

本地是好的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值