"The File not found error is causing a problem with the Ionic 5 File Opener

I am currently utilizing Ionic with Angular to develop an application. Within my app, I incorporate CouchDB for downloading images.

My device of choice is an Android Phone.

During my attempt to download a file using the file opener, I encountered the following error message:

(Status:9 message:file not found)

<ion-item mode=md class="input-group ion-no-padding viewFile" lines=none *ngIf="common.isDocumentFill">
     <span (click)="doc(fc)">View File</span>
    </ion-item>

//function

doc(objFC) {

    let obj = {
      ServiceId: 1,
      CouchDBDocId: objFC.CouchDBDocId,
      DocumentName: objFC.FileName
    }
    this.api.getPdf(obj).subscribe((data: any) => {
     // debugger
      let blob = new Blob([data], { type: data.type });

      var downloadURL = window.URL.createObjectURL(data);
      var types = data.type
      this.down(downloadURL, types)
    }); 
 }
  down(filepath, mimeType) {
    this.fileOpener.open(filepath, mimeType)
     .then(() =>
     console.log('File is opened')
      )
     .catch(e => console.log('Error opening file', e)); 
    }

   

and Service

 getPdf(obj) {

    // debugger
    const httpOptions = {
      responseType: 'blob' as 'json'
    };

    return this.http.post(this.url + "DocumentDetails/DownloadFile", obj, httpOptions);
  } 

Answer №1

To proceed, please ensure all necessary plugins are installed

1.import { FileOpener } from '@ionic-native/file-opener/ngx';    
2.import { File } from '@ionic-native/file/ngx';

Create instances in the constructor

  constructor(
         private fileOpener: FileOpener,
         private file: File
         )

Add the following function to your TypeScript file

openPDF (stringBase64PDF) {
                debugger
                fetch('data:application/pdf;base64,' + stringBase64PDF, {
                    method: "GET"
                })
                .then(res => res.blob()).then(blob => {
                  console.log("created blob");
                  this.file.createFile(this.file.dataDirectory, 'temp.pdf', true)
                  .then(() => {
                    console.log("file created");
                    this.file.writeFile(this.file.dataDirectory, 'temp.pdf', blob, { replace: true })
                    .then(res => {
                      console.log("file writed");
                      this.fileOpener.open(res.toInternalURL(), 'application/pdf')
                      .then((res) => {
                        console.log('file opened')
                      }).catch(err => {
                        console.log('open error')
                      });
                    }).catch(err => {
                      console.log('write error')     
                    });
                  }).catch(() => {
                    console.log("create error");
                  })
                  
                }).catch(err => {
                  console.log('blob error')
                });
              }

Add the following code snippet to your HTML file

  <ion-item (click)="openPDF(base64pdf)">
             <ion-label>Click here to open pdf file</ion-label>
            </ion-item>  

Answer №2

Consider generating the URL in this way:

let downloadURL = (window.URL || window.webkitURL).createObjectURL(data);

If the browser does not support window.URL, check out more details here.
Are you referring to an iOS or Android device specifically?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Troubleshooting: Author information not appearing in posts (AngularJS, $http, MongoDB) - Comprehensive guide on MEAN Stack

I recently started learning MEAN Stack Web Development and have been following the tutorial at mean-stack-tutorial. I reached the section on authenticating users, and everything seems to be working well with no console errors. However, in my MainCtrl withi ...

Is it possible to make the info box centered and adjust everything to seamlessly fit on all screen sizes?

Is there a way to create a centered info box that stretches to fit any screen size? ...

Modifying state within reducers is not allowed

Encountered the following error while using @ngrx/store: index.js?4b23:19 State mutation is prohibited inside of reducers. (anonymous) @ index.js?4b23:19 (anonymous) @ index.ts:54 rootReducer @ index.ts:70 _initialStateFactory @ ng2.ts?2a33:24 AppModule ...

Angular material dialog box experiencing issues with saving multiple values

Currently, I am utilizing Anular9 and implementing mat-raised-button in the following manner: <button mat-raised-button (click)="saveClick()" color="primary"><mat-icon>check</mat-icon>&nbsp;&nbsp;Ok</butto ...

Can you explain the functionality of this Angular CLI instruction?

Can you explain the function of this command in the Angular command line? npx ng g s weather --flat false Referenced in: Angular 6 for Enterprise Ready Web Applications, page 61 ...

The GET API is functioning properly on Google Chrome but is experiencing issues on Internet Explorer 11

Upon launching my application, I encountered an issue with the v1/validsColumns endpoint call. It seems to be functioning properly in Chrome, but I am getting a 400 error in IE11. In IE v1/validCopyColumns?category=RFQ&columns=["ACTION_STATUS","ACTIO ...

Issue arises when integrating Angular 13 with ngrx and OAuth2: encountering difficulties in creating an effect

Currently, I'm following an example that uses an earlier version of Angular and ngrx. You can find the tutorial on NGRX Authentication in Angular with asp.net core here. This is what my Auth.action.ts file looks like: import { createAction, props } f ...

Top method for organizing Vue JS elements

I am looking to integrate a search feature on my website using Vue 2, where the search functionality will be applied to components generated from a JSON file upon page load. The JSON file contains the keywords I want to utilize for the search - specifical ...

Collaborate on Firestore collection paths between administrators and web users

Seeking a solution to create reusable functions that can access Firestore Document/Collection references in both web and admin (node.js) environments. For instance: getUserDocumentReference(company: string, user: string) { return firebase.collection(&qu ...

Attempting to change the primary color in Bootstrap is ineffective following a button click

I have been attempting to customize the primary color of Bootstrap 5 using SCSS. Everything works perfectly until I click a button that opens an external link. Below is the content of my SCSS file: $primary: #ae217aff; @import "../node_modules/boots ...

What is the best way to utilize state and an object's keys in React to dynamically style components?

I am working with Create React App (CRA) and Axios, and I'm facing a specific challenge. I want to create a basic stock chart that showcases exchange rates. The component should load on mount, make a call to a static API using Axios, and populate the ...

Triggering the creation of an Algolia Index from Firestore operations like updates, deletions, and additions is causing significant delays

I'm currently developing an application with Algolia integration and Firebase compatibility. To utilize Algolia's features, I have incorporated the firebase extension from this link. This allows for real-time synchronization of data between Fire ...

There is a syntax error that occurs when attempting to begin a key with a hyphen (-)

Upon initializing the following object, an error is thrown. var postData ={ file_path : "https://s3-us-west-2.amazonaws.com/ps/eams/6-48K.mxf", template_type : "1", template_name : "Basic Tests", job_type : "0", user_note : "my job", access-ke ...

Rendering Meta Tags in Angular 4

Is there a way to detect when Meta tags have finished rendering? In my Angular 4 application, I have dynamic routes set up like this: const routes: Routes = [ { path: 'products/:slug', component: ProductComponent } ]; Inside the ProductCompo ...

Discovering the functionality of es6 object.assign and find methods within a typescript file

Currently, I am in the process of transitioning from Java Script to TypeScript for my project. However, I am facing limitations as I am unable to utilize object.assign() and find methods. ...

Encountered an error: $(...).DataTable is not recognized when attempting to call three separate tables on the same page with auto refresh enabled

Hello, I am new to using scripts and I am attempting to load three different tables onto my webpage, all populated from a MySQL database. Additionally, I want all three tables to automatically refresh when new data is inserted or changed. I have successful ...

Renovating Code: Swapping out a data type (and refreshing imports) - Tips and Tricks

For example, in our code base, we currently utilize a type OldType from the npm package @old-package. Our goal is to substitute it with our custom type NewType, which can be accessed through @new-package. Illustration Existing imports import { AnyImport ...

The HTML was generated without any styling properties assigned

After running my script on a galaxy tab, I encountered a strange issue. I created an HTML element (div) and attempted to access the style attribute, only to receive an error message indicating that style is null. Below is the code snippet: var newDiv = d ...

Is there a method available to retrieve the video duration prior to uploading it?

Is there a method to restrict users from uploading videos longer than 30 seconds? ...

Retrieving an image from a JSON file based on its corresponding URL

I am trying to extract the URL and display it as an image: This is how it appears in JSON: https://i.sstatic.net/vpxPK.png This is my HTML code: <ul> <li *ngFor="let product of store.Products"> <p>Product Image: {{ product.Pr ...