【问题标题】:How can i able to convert pdf, xlsx and doc file in base64 data in ionic 3?如何在 ionic 3 中转换 base64 数据中的 pdf、xlsx 和 doc 文件?
【发布时间】:2019-02-15 13:07:12
【问题描述】:

我的代码是:

addFilesforRNAppz(inputFile: any) {
 const fileget = this.fileInputVariable.nativeElement.files;

 let fileList: FileList = inputFile.target.files;

 // I can access the selected file name, size and object correctly without any issues
 console.log("File name = " + fileList[0].name);
 console.log("File size = " + fileList[0].size);
 console.log("File = " + fileList[0]);

 // Converting the file input to base 64 (This rarely works)
 this.convertFileToBase64AndSet(fileList);

 // ===============================================================
}
convertFileToBase64AndSet(fileList: FileList)
{
   if(fileList.length > 0)
  {
    var reader = new FileReader();

      reader.onloadend = (e: Event) => {

      console.log(reader.result);
    }

    reader.readAsDataURL(fileList[0]);
  }
}


<input type="file" #inputFile (change)="addFilesforRNAppz($event)" class="file-input" />

我想要所选 pdf 或任何 doc 文件的 base64 数据。我可以将 Image 转换为 base64,但它不会从 pdf 转换为 base64 数据。

我的代码有什么问题,请尽快给出解决方案,不胜感激。

【问题讨论】:

    标签: typescript ionic3


    【解决方案1】:

    我可以将 Image 转换为 base64,但它不能从 pdf 转换为 base64 数据。

    您的阅读代码对imgpdf 或其他任何东西都一样。但是我怀疑您正在尝试将读取值用作data-urisrc。这不适用于pdf 文件,仅适用于图像。

    【讨论】:

    • 是的,我遇到了同样的问题。我也无法转换 pdf 或任何 doc 文件。那么是否有任何其他功能或任何其他代码适用于 pdf 或 doc? @basarat
    • 如果您有任何其他建议,请告诉我。谢谢:)
    • 那么,pdf转base64数据的解决方案是什么?
    【解决方案2】:

    要转换 pdf,您可以使用:

    file.readAsArrayBuffer(filePath, fileName)
    

    以下是filechooser插件获取的pdf阅读完整代码:

    this.fileChooser.open().then((uri) => {
           this.filePath.resolveNativePath(uri).then((finalUri) => {
             this.file.resolveLocalFilesystemUrl(finalUri).then((entry) => {
              let filePath = entry.nativeURL.substring(0, entry.nativeURL.lastIndexOf('/'));
              if (entry.name.endsWith('.pdf')){
                return this.file.readAsArrayBuffer(filePath, entry.name)
                  .then((data) => {
                    //data after reading pdf
                  })
                  .catch((error) => {
                    //error
                  });
              }
            })
          })
        })
    

    【讨论】:

    • 您好@Shrutika Patil,我尝试了您的解决方案,但出现错误 FileError code:13,message:"input is not a directory"
    • 您能否阅读 readAsArrayBuffer 的文档以了解文件路径所需的格式?你需要先使用文件插件然后你会得到一个文件的uri,然后将它转换成本地文件系统后你会得到一个路径
    • 我已经编辑了我的答案并提供了在我的项目中运行的完整代码。请尝试一下。
    猜你喜欢
    • 2018-09-12
    • 2019-01-24
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2012-04-03
    • 2019-02-05
    • 1970-01-01
    相关资源
    最近更新 更多