如何在离子中保存Blob

时间:2017-12-04 14:12:00

标签: pdf ionic-framework ionic2 blob

我是离子框架的新手,实际上我将字节数组作为来自后端服务的响应并将其转换为blob。如何以离子形式将其保存为PDF?

var blob = new Blob([res], { type: 'application/pdf' });

这里res是来自服务的响应(字节数组)。

代码

var blob = new Blob([res], { type: 'application/pdf' });         

        let fileName="Receipt.pdf";         
        let filePath = (this.platform.is('android')) ? 
        this.file.externalRootDirectory : this.file.cacheDirectory;

        this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry) => {

          console.log("File created!");          
          this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
            .then(() => console.log('File is opened'))
            .catch(err => console.error('Error openening file: ' + err));
        })
          .catch((err) => {
            console.error("Error creating file: " + err);
            throw err;  
          });

提前致谢。

1 个答案:

答案 0 :(得分:2)

为了保存PDF,您需要使用一些cordova插件。 Ionic围绕这些here有一些不错的包装。查看文件,文件传输和文件打开器插件。

以下是您将这些插件合并到项目中后可以使用的一些示例代码:

    var blob = new Blob([res], { type: 'application/pdf' });

    //Determine a native file path to save to
    let filePath = (this.appConfig.isNativeAndroid) ? this.file.externalRootDirectory : this.file.cacheDirectory;

    //Write the file
    this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry: FileEntry) => {

      console.log("File created!");

      //Open with File Opener plugin
      this.fileOpener.open(fileEntry.toURL(), data.type)
        .then(() => console.log('File is opened'))
        .catch(err => console.error('Error openening file: ' + err));
    })
      .catch((err) => {
        console.error("Error creating file: " + err);
        throw err;  //Rethrow - will be caught by caller
      });