Learn the steps to access various file formats including doc, ppt, xlsx, pdf, jpg, and png using the Ionic native file opener

I am currently working on a Hybrid app using Ionic. My goal is to be able to open various types of files (doc, ppt, xlsx, pdf, jpg, png) from the device's internal or external storage using the Ionic Native File Opener plugin. However, I have only been successful in opening PDF files with the code below. When trying to open other file types, what should I replace 'application/pdf' with? Any assistance would be greatly appreciated. Thank you.

import { FileOpener } from '@ionic-native/file-opener';

constructor(private fileOpener: FileOpener) { }

...

this.fileOpener.open('path/to/file.pdf', 'application/pdf')
  .then(() => console.log('File is opened'))
  .catch(e => console.log('Error openening file', e));

Answer №1

Finally found the solution!

let fileExtn = file_name.split('.').reverse()[0];
let fileMIMEType = this.getMIMEtype(fileExtn);
         this.fileOpener.open("file:///storage/emulated/0/download/" + file_name, fileMIMEType)
                .then(() => console.log('File is opened'))
                .catch(e => console.log('Error opening file', e));

Create another function for MIMEtype

getMIMEtype(extn){
  let ext = extn.toLowerCase();
  let MIMETypes ={
    'txt' :'text/plain',
    'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'doc' : 'application/msword',
    'pdf' : 'application/pdf',
    'jpg' : 'image/jpeg',
    'bmp' : 'image/bmp',
    'png' : 'image/png',
    'xls' : 'application/vnd.ms-excel',
    'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'rtf' : 'application/rtf',
    'ppt' : 'application/vnd.ms-powerpoint',
    'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
  }
  return MIMETypes[ext];
}

Answer №2

Alright, so I created a file named file-extension.ts in my provider directory which contains a variety of extensions along with their respective headers. Here's the code excerpted from Mozilla Docs (for full reference, visit here):

file-extension.ts:

export const FILE_EXTENSION_HEADERS = {
    // Extension headers listed here
};
  • I later imported this into my provider file and implemented a method to make these headers accessible application-wide.

APIService.ts:

import { FILE_EXTENSION_HEADERS } from './file_extension_headers';


@Injectable()
export class APIService{
  /* Additional methods */

    fetchFileHeader(extension){
        extension = extension.toLowerCase();
        return FILE_EXTENSION_HEADERS[extension] !== undefined ? FILE_EXTENSION_HEADERS[extension] : 'text/plain';// default header if none found
    }
}
  • Keep in mind that even with the appropriate header, some files may still require specific applications installed on your mobile device in order to open them.

Answer №3

In order to correctly utilize the file:/// path, it is essential because post sdk 16, only paths without file:/// are accepted.

let path = "your path (file:///storage/emulated/0/)";
let tempVal = path.split('///');

this.fileOpener.open(tempVal[1] + this.qrImgName + '.jpg', 'image/jpeg')
  .then(() => console.log('File is opened'))
  .catch(e => console.log('Error opening file', e));

In this scenario, tempval holds the path beyond the "file:///", resembling storage/emulated/0/, while qrImgName represents the variable containing the desired image name to be opened.

Hence, the final open URL appears as "storage/emulated/0/imagename.jpg".

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

The @Hostlistener method consistently returns an 'undefined' value when passing in the @Input() value

I'm encountering an issue where the value from @Input() is undefined in my @Hostlistener method. What could be causing this? export class InputHelpComponent implements OnInit { isOpened: boolean = false; @Input() field!: string; @HostListener(& ...

Encountering issues during the installation of the Angular/CLI software

Whenever I execute the command below: npm install -g @angular/cli I encounter this error message: C:\Users\AA>npm install -g @angular/cli npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f ...

npm error - The module './selenium-webdriver/lib/input' cannot be located

After updating my Angular project from version 5 to 7, I encountered numerous vulnerabilities. To address this, I followed the suggested commands in "npm audit" which successfully fixed all the vulnerabilities. However, when attempting to run: ng serve ...

The functionality of Angular Signal computation fails to accurately reflect the number of items contained within an array

Currently, I am working on a service that handles items. itemList= signal<Item[]>([]); reset(){ this.itemList.set([]); } add(item){ this.itemList.update(list => { const ind = list.findIndex(o => o._id == item._id); if (ind !== -1) { ...

Is there a way to have my accordion adjust automatically?

I have developed a dynamic accordion component that populates its values from the parent component. However, I am facing an issue where each accordion does not respond individually to clicks. Whenever I click on any accordion, only the first one expands an ...

Exploring the world of Angular CLI testing and the versatility of

Struggling with integrating Angular CLI's test framework and enum types? When creating an enum like the following (found in someenum.ts): const enum SomeEnum { Val0, Val1 } Utilizing it in this way (in app.component.ts): private someEnum = Some ...

Building a MEAN stack application using Angular 5 and implementing passportJS for authentication

What's the process for implementing authentication in a MEAN stack using Angular 5, Node.js, and Passport.js? ...

Fetching Data from Response Headers in Angular 4.3.3 HttpClient

(Text Editor: Visual Studio Code; TypeScript Version: 2.2.1) The main objective here is to fetch the headers of the response from a request Let's consider a scenario where we make a POST request using HttpClient within a service: import { Injec ...

There is a complete absence of text appearing on the html page when Angular is

Currently, I am in the process of learning Angular during my internship. As part of the requirements, I have been tasked with developing a client-server application using Angular as the frontend framework and Spring as the backend solution. Within the proj ...

Loading a view in Ionic2 with Angular2 after a successful subscription

After completing an http post request, I want to navigate to the next view in my app. Here is a breakdown of the three services I am using: The server service handles generic http calls such as get and post requests. The city service stores a list of ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

Updating validation patterns dynamically in Angular during runtime

I currently have a template-driven form with pattern validation that is functioning correctly: <input type="text" [(ngModel)]="model.defaultVal" name="defaultVal" pattern="[a-zA-Z ]*" /> <div *ngIf="defaultVal.touched || !defaultVal.prist ...

Empty array returned on click using Angular 5 with chart.js

I've been struggling with getting the onclick function in chart.js to work properly. I came across the getElementsAtEvent(event) function which should supposedly return an array containing the data of the clicked part of the chart. However, all it ret ...

converting HTML values to TypeScript

I'm a beginner with Angular and could use some assistance. Currently, I have two components - one for the index and another for navigation. Within the index component, there are subcomponents that change based on the value of a variable called produ ...

The value of form.formGroup is not equivalent to the output of console.log(form)

Having an issue here. When I send a Form to a component, If I use console.log(form), it displays the object correctly. However, when I check the form in the console, the form.formGroup.value looks fine (e.g. {MOBILE0: 'xxx', PHONE0: 'xxx&ap ...

Trouble uploading an audio blob as a base64 string using Google Drive API with the drive.files.create method - File ID could not be located

My current challenge involves sending an audio blob to a specific Google Drive folder. To accomplish this, I convert the blob into a file before initiating the transfer process. However, I have encountered an error from the beginning: Error: File not fo ...

Angular input material with a stylish twist

How can I style all inputs on the Angular Material input component (matInput) using Typescript? I attempted to implement this solution, but it only affects the first element. ngAfterViewInit () { const matlabel = this.elRef.nativeElement.querySelecto ...

What is the best method to calculate the total of multiple input values from various cells and display it in the final cell of an Angular table?

Hey there! I have a challenge where I need to calculate the sum of input values for each cell and display it dynamically in the last cell of the row. Take a look at the image below: https://i.stack.imgur.com/0iKEE.png In the image, you can see that the nu ...

Guide to connecting data from the backend to the frontend in the select option feature using Angular 9

I have a backend system where I store a number representing a selected object, which I am trying to display in a select option using Angular. Currently, the select option only displays a list of items that I have predefined in my TypeScript code using enu ...

The 'append' property is not present in the 'Headers' type in Angular 2

import { HttpClient, HttpHeaders } from '@angular/common/http'; export class LoginService { let headers: HttpHeaders = new HttpHeaders(); headers = headers.set('Content-Type', 'application/json'); } I encounter ...