Exploring sdcard files in your Ionic 3 application

I am a newcomer to Ionic 3 and facing an issue while trying to upload documents from a device. I have used Android permissions for storage access but I am only able to access the internal storage of the device. My goal is to access files from the SD card. Below is the code snippet I am working with:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { RemoteServiceProvider} from "../../providers/remote-service/remote-service";
import { AndroidPermissions } from '@ionic-native/android-permissions';

@IonicPage()
@Component({
 selector: 'page-home',
 templateUrl: 'home.html',
 })
export class HomePage {

 android: AndroidPermissions;
 constructor(public remoteServiceProvider: RemoteServiceProvider, public 
 navParams: NavParams, public nvCtr: NavController) {
//this.getStates();
this.android= new AndroidPermissions();
this.android.requestPermissions([this.android.PERMISSION.READ_EXTERNAL_STORAGE,this.android.PERMISSION.WRITE_EXTERNAL_STORAGE])


  }

  getStates(){
this.remoteServiceProvider.getResult().subscribe(data => {
  alert(data._body);
},error => {
  alert(error);
});

 }
 ionViewDidLoad() {
  console.log('ionViewDidLoad HomePage');

 }

}

After granting permissions to the user, the code snippet below shows how I am accessing the files:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FileChooser } from '@ionic-native/file-chooser';
import { FilePath } from '@ionic-native/file-path';
import { File } from '@ionic-native/file';
import {Platform} from "ionic-angular";
@IonicPage()
@Component({
 selector: 'page-document',
  templateUrl: 'document.html',
})

export class DocumentPage {
fileChooser: FileChooser;
filePath: FilePath;
nativepath: any;
file: File;

constructor(public navCtrl: NavController, public navParams: NavParams) {
this.fileChooser= new FileChooser();
this.filePath= new FilePath();
this.file=new File();
}

ionViewDidLoad() {
  console.log('ionViewDidLoad DocumentPage');
}

openFile(){
this.fileChooser.open()
.then(uri => this.convertFilePath(uri))
.catch(e => alert(e));
}

convertFilePath(filePathUri: string){
this.filePath.resolveNativePath(filePathUri)
.then(filePath =>{
  this.nativepath= filePath;
  //Here in nativepath we get filepath
})
.catch(err => alert("filePath "+err));
}

}


After granting user permissions, the code snippet above shows how I am accessing the files:

openFile(){
   this.fileChooser.open()
   .then(uri => this.convertFilePath(uri))
   .catch(e => alert(e));
}

convertFilePath(filePathUri: string){
 this.filePath.resolveNativePath(filePathUri)
 .then(filePath =>{
  this.nativepath= filePath;
  //Here in navtivepath i get the file path
 })
 .catch(err => alert("filePath "+err));
}

Answer №1

If you want to achieve this, consider utilizing the Native plugin file. This plugin provides a File API which enables read/write access to files stored on the device.

The File class offers static convenience functions for interacting with files and directories.

 ionic cordova plugin add cordova-plugin-file
 npm install --save @ionic-native/file

For Android, make sure to utilize the externalRootDirectory instance member.

On Android, this refers to the external storage (SD card) root directory.

Refer to the GitHub repository for more information.

Answer №2

If you're looking for a solution, this code snippet could be helpful:

import { File } from "@ionic-native/file";
import { Diagnostic } from "@ionic-native/diagnostic";

constructor(
    ...
    public file: File,
    public diagnostic: Diagnostic
){

this.diagnostic.getExternalSdCardDetails()
.then( (data) => {
  this.jcError += "\n" + "sd:" + JSON.stringify( data);
  this.jcError += "\n" + "Number cards: " + data.length;
  for( let ii = 0; ii < data.length; ii += 1){
    let thisElem = data[ii];
    if( thisElem.type.toLowerCase() === "application" && thisElem.canWrite){
      this.ourSDentry = thisElem;
      basePathSD = thisElem.filePath;
      break;
    }
  }
  if( !basePathSD){
    this.jcError += "\n\n" + "no SD card found";
    return;
  }
}, (errData)=>{
  tag = "getExternalSdCardDetails";
  this.jcError += "\n\n" + tag + ":ERR:" + JSON.stringify( errData);
});

After executing this code, you can utilize the basePathSD variable to interact with the SD card.

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

What is the process for uploading a raw image with AJAX?

Looking for advice on the best way to upload a base64 encoded image from a mobile device's camera using PhoneGap to store it on a server. Any recommended approaches? Encountering Error 414 (Request-URI Too Large) when attempting to include the base64 ...

The issue lies within typescript due to process.env.PORT being undefined

I am a newcomer to working with TypeScript. Even after importing and using the dotenv package, I am still encountering issues with getting undefined values. Do I need to declare an interface for the dotenv variables? import express,{Application} from &apo ...

Make the image take up the entire screen in HTML

My goal is to display an image that fills the entire screen. Here's how my HTML code looks: <!DOCTYPE html> <html lang="de"> <head> <meta charset="utf-8" /> <title></title> </head> ...

Is it appropriate to utilize a constructor for tasks beyond simply initializing variables in Java?

In my current projects involving Android and Java, I am faced with the task of creating a class to draw a rectangle on the canvas. My question is whether it is considered good practice to have a constructor that does more than just initialize variables. Wh ...

Establishing the Volley for a Nested RecyclerView Configuration

I am working on creating a menu list for a cake shop, which will have 3 categories with different menus in each category. I have successfully implemented a nested RecyclerView, but I am facing a challenge in connecting the RecyclerView with the database. ...

Learn how to upload files from Angular 2 and send them to a server URL using ng2-fileupload

I am currently utilizing ng2-file-upload for file uploads on the front end. Within my HTML, I have the following code: <input type="file" ng2FileSelect [uploader]="uploader" /> In my TypeScript file, I receive the uploaded file in a change event ...

Saving selected language in Angular using ngx-translate

I am facing an issue with ngx-translate for translation. Whenever I select a language, it gets saved in localStorage. However, upon refreshing the page or navigating to another page, it reverts back to the default keys instead of the selected language. Be ...

What is the proper way to define an array of objects in TypeScript?

In search of a way to define a function that accepts an array of unspecified object types, known as "anonymous types." I want to enforce strict typing with TypeScript. The objects in the array all have properties like name, price, and description. bagTotal ...

Navigating in Angular to initiate file retrieval

Is there a way to set up a route in Angular that allows me to download a file? For example, having a route like '/myFile' would result in downloading the file "/assets/files/test.pdf". I've tried using the redirectTo option for routing, bu ...

Error when connecting to AWS AppSync through Flutter: Ssocket exception

I have encountered an issue while working on a Flutter application with AWS AppSync. I am using the endpoint URL provided by the AWS server, but when attempting to execute a query, I am receiving the following error: Even though I am in a proxy setting, i ...

I'm deciding which "Icon Type" to select for regular images for an Android app. What is the best way to incorporate them as ImageViews?

I need the pictures to remain in their original state, unaltered. My goal is to incorporate some default images provided by Android Studio (Asset Type: Clip Art). These images will be utilized as ImageViews on the main screen of the app, and nowhere else. ...

How can I store the status of checked and unchecked checkboxes in an array of objects using Angular 7?

I have a set of checkboxes with a parent-child structure, and their values are generated dynamically in a loop. When I click the submit button, I want to capture the selected or unselected values in the specified format (as shown in the commented output) ...

It is imperative that the 'Access-Control-Allow-Origin' header value in the response is not set to '*' when the request's credentials mode is 'include'

I am currently working on establishing a connection using socket.io between Angular and a Node.js Server Within Angular, I have set up a new socket by importing socket.io-client and connecting it as follows: import * as io from 'socket.io-client& ...

Testing MatDialog functions in Angular: Learning how to open and close dialogues

I am currently facing an issue with testing the MatDialog open and close functions. No matter what I try, I cannot seem to successfully test either the open or close functions. I am wondering how I can mock these functions in order to properly test them. W ...

Help! My Angular CLI version 8.2.2 is displaying squares instead of the Font-awesome icons

I successfully added Font Awesome using the command npm install --save font-awesome angular-font-awesome from https://www.npmjs.com/package/angular-font-awesome. After linking it in my angular.json file: "styles": [ "src/styles.css", "node_modu ...

Exploring Angular 2: Unlocking the Power of Directives within Components

To display a dialog component on the main component page after clicking a button, I used directives in the following way: Within the template: <button id="goToTasksCases" class="btn btn-success btn-lg" (click)="doShowStartNewCase($event)">START A N ...

The connection named "default" was not located

Error ConnectionNotFoundError: Connection "default" was not found. I encountered this error when I implemented the dependency inversion principle in my project. ormconfig.json { "name": "default", "type": " ...

What is the most effective way to extract data that includes an array within it?

const flightList = [{ number: 343, from: "Singapore", to: "India", upgradeTypes: ["Economy to Premium Economy", "Economy to Business Class"] }, . { number: 363, from: "Chennai", to: "Sing ...

Developing applications using the combination of Vue.js, JSX, and

While I have no issues using TypeScript with single file components (.vue files), I encountered problems when attempting to use it with JSX files. Two errors arise, one in my index.ts file. I'm uncertain if there was a mistake made in my configuration ...

typescript code: transforming object values into keys in typescript

Here is a scenario: const obj1 = { a: 'x', b: 'y', c: 'z', } I am looking to automatically create a type like this: type Type = { x: number, y: number, z: number, } I initially considered the following approach: ...