如何在Ionic中保存Blob

Kum*_*mar 5 pdf blob ionic-framework ionic2

我是离子框架的新手,实际上我从后端服务获取字节数组作为响应并将其转换为Blob。如何将其保存为离子型PDF?

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

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;  
          });
Run Code Online (Sandbox Code Playgroud)

提前致谢。

BRa*_*ass 5

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

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

    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
      });
Run Code Online (Sandbox Code Playgroud)