Images are failing to load in Ionic 3

Currently working on developing an Ionic application and troubleshooting the use of the camera native plugin. The script functions flawlessly in a fresh project, but encounters issues within the current project environment.

Initially suspected a problem with the package.json file, yet after updating all packages and reinstalling plugins, including file and camera, the issue persists. Here's the output I receive: https://i.sstatic.net/1EjLX.jpg

Interestingly, when testing the script in a new project, the photo displays perfectly!

Seeking guidance as I am at a standstill and unsure where to investigate for potential conflicts or errors.

HTML:

<ion-card *ngIf=resultImageArray>
  <img src="{{ resultImageArray }}" />
</ion-card>

TS:

import { Component } from '@angular/core'; 
import { NavController, ToastController } from 'ionic-angular';
import {Camera, CameraOptions} from "@ionic-native/camera";
import {File} from '@ionic-native/file';
export class HomePage {

public imageURI: any;
public imageName: any;
public fileCreated: boolean = false;
public imageString: any;
resultImageArray: any;
constructor(public navCtrl: NavController, private file: File, private 
camera: Camera, private toastCtrl: ToastController,) {}
getImageFromCamera() {
const options: CameraOptions = {
    quality: 20,
    saveToPhotoAlbum: true,
    destinationType: this.camera.DestinationType.FILE_URI,
    sourceType: this.camera.PictureSourceType.CAMERA,
    encodingType: this.camera.EncodingType.JPEG,
    allowEdit: true
};

this.camera.getPicture(options).then((imageData) => {
    this.imageURI = imageData;
    this.imageName = imageData.substr(imageData.lastIndexOf('/') + 1);
    this.file.checkDir(this.file.externalRootDirectory, 'ImagesDemo')
        .then(() => {
            this.fileCreated = true;
        }, (err) => {
            console.log("checkDir: Error");
            console.log(JSON.stringify(err));
            this.presentToast("checkDir Failed");
        });
    if (this.fileCreated) {
        this.presentToast("Directory Already exist");
    }
    else {

 this.file.createDir(this.file.externalRootDirectory,"ImagesDemo",true)
            .then((res) => {
                this.presentToast("Directory Created");
            }, (err) => {
                console.log("Directory Creation Error:");
                console.log(JSON.stringify(err));
            });
    }

    let tempPath = this.imageURI.substr(0,this.imageURI.lastIndexOf('/')+1);
    let androidPath = this.file.externalRootDirectory + '/ImagesDemo/';
    this.imageString = androidPath + this.imageName;

    this.file.moveFile(tempPath, this.imageName, androidPath,this.imageName)
        .then((res) => {
            this.presentToast("Image Saved Successfully");
            this.readImage(this.imageString);

        }, (err) => {
            console.log("Image Copy Failed");
            console.log(JSON.stringify(err));
            this.presentToast("Image Copy Failed");
        });

    this.toDataURL(this.imageURI, function (dataUrl) {
        console.log('RESULT:' + dataUrl);
    });
    }, (err) => {
    console.log(JSON.stringify(err));
    this.presentToast(JSON.stringify(err));
    });
}


presentToast(msg) {
let toast = this.toastCtrl.create({
    message: msg,
    duration: 2000
});
toast.present();
}

toDataURL(url, callback) {
let xhr = new XMLHttpRequest();
xhr.onload = function () {
    let reader = new FileReader();
    reader.onloadend = function () {
        callback(reader.result);
    };
    reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}

readImage(filePath) {
let tempPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let imageName = filePath.substr(filePath.lastIndexOf('/') + 1);

this.file.readAsDataURL(tempPath, imageName)
    .then((res) => {
        this.presentToast("Image Get Done");
        this.resultImageArray = res;
    }, (err) => {
        this.presentToast("Image Get Error");
    });
}
}

Upon remote debugging the app, encountered the following error in the console:

(index):1 Refused to load the image 'data:image/jpeg;base64,/9j/4QBAAl+B//2Q==' due to Content Security Policy directive violation. Specifically, "default-src *" is invoked without explicit setting of 'img-src', utilizing 'default-src' as fallback.

Edit was made by redacting lengthy base 64 code for readability purposes. Puzzled by why it performs seamlessly in new projects while encountering complications in this particular one.

Answer №1

After some trial and error, I finally managed to solve the issue and wanted to share my solution with others who might be facing the same problem.

I made a modification in my index.html file by adding the following line:

<meta http-equiv="Content-Security-Policy" content="default-src *; 
style-src 'self' 'unsafe-inline'; 
script-src 'self' 'unsafe-inline' 'unsafe-eval';
img-src 'self' data: https://s-media-cache-ak0.pinimg.com;
script-src 'self' https://maps.googleapis.com;
" />

Now, all functionalities are working perfectly without any issues.

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

Event cancellation received from IncomingMessage

I have a simple express server running on Node with versions 4.13.3 and 4.2.3, respectively. //initialization code app.put('/', function(req, res) { req.on('close', function() { console.log('closed'); }); req.on( ...

Tooltips remain inactive on the first plot until there is a change in the plot, triggering their functionality

I've encountered a strange issue with tooltips using d3-tip in a scatter plot. Initially, the tooltips are not functioning at all, and even the mouseover events are not triggering as expected. The scatter plot consists of three sets of data on each a ...

What is the process for defining a default value for a template-driven form input in Angular 2?

I have a simple input element in my form that requires a default initial value to be set. <input type="number" name="interest_rate" [(ngModel)]="interest_rate"> In my code, I included this.form.controls['interest_rate'].patchValue(this.a ...

The success callback method is no longer correctly referencing the variable due to a change in the AJAX request

Imagine you have a table in your HTML file with the following rows, where {{ }} represent variables: <tr id="{{ object.id }}"> <td class="name">{{ object.name }}</td> </tr> <tr id="{{ object.id }}"> <td class="nam ...

Using Javascript to organize data in a table

I have a basic HTML table setup that looks like this: <table id="myTable"> <thead> <tr> <th class="pointer" onClick="sortTable()">Number</th> <th>Example3</th> <th ...

Having trouble with JQuery click function not executing on initial click?

As I scoured through various resources looking for solutions to issues similar to mine, I stumbled upon numerous helpful insights. However, after going through approximately 15 of them, I hit a roadblock in finding someone who has encountered the exact sam ...

What is the method for setting a default image to be preloaded in filepond?

Currently, I am working on a Laravel view for editing a record which includes an associated image. My goal is to have the image preloaded inside the input file so that when you submit the form, the same image is sent or you can choose to change it. // Con ...

Problems with updating HTML/Typescript in Visual Studio and Chrome are causing frustration

While working on my company's application locally and making HTML/TS changes, I am facing an issue. Whenever I save/hot reload and refresh the browser, no changes seem to take effect. I've tried stopping debugging, building/rebuilding, and runni ...

Using AJAX to Query a PHP Database

Currently, I am implementing an AJAX call from the YouTube player JavaScript to a PHP page that contains various functions, mainly involving database inserts. In my PHP code, I use a case statement to determine which function is being called based on the d ...

What are some strategies for stopping a form from redirecting me while utilizing ReactJS and ExpressJS?

Recently, I created a form that redirects to the route /repair upon submission with an action of /repair. However, I would prefer to keep it as a Single Page Application (SPA) where after submitting the form, the fields are cleared, and a simple message l ...

Update the network name in the Axios request

Currently, I am utilizing Axios for handling both GET and POST requests. One question that has been on my mind is how to modify the network name: At present, the name serves as the parameter accompanying each request. However, I ponder whether it's f ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

Click event to focus on AngularJS TinyMCE textarea

My current project utilizes the tinymce text editor in combination with the angularJS framework. I obtained the directive from here and successfully integrated the editor using the provided example on GitHub! Initially, everything was working smoothly wit ...

Is there a way to convert a string containing a date calculation, such as "now + 1 day", into a date object?

Currently, my team is utilizing Cucumber to define our test cases within string-based feature files. Our integration tests are executed against a wiremock stub that contains date calculations such as: "{{now offset='+15 minutes'}}" I am seeking ...

What is the location of the Typescript project path in Visual Studio 2015 Cordova?

In my development journey, I decided to create a Typescript blank Cordova project within Visual Studio 2015. After adding a small test bit of ts code... function onResume() { // TODO: This application has been reactivated. Restore application st ...

A Simple Guide to Setting a Background Image in React Native with the Nativebase.io Library

What is the process for including a background image in React Native with the help of the Nativebase.io Library? I have a specific screen where I need to incorporate a background image, with all other elements positioned at the center of the image. ...

Is jQuery utilized by the bootstrap-grid system?

Finale: In our current setup, we are utilizing Angular 9, and like many frontend frameworks, there is a preference against incorporating other JavaScript libraries alongside the framework for manipulating the DOM. The Challenge: I am hesitant to include ...

What is the best way to delete and add elements in a looped array using Javascript

i have a form similar to this one. how can I replace this form each time the country changes, by removing it and then appending it again from a looping array. If there is only one set of data, display an "Add Form" Button; however, if there is more than o ...

What is the regular expression that allows numbers between 1 and 24, including decimals?

Can anyone help me create a regex expression that only allows numbers between 1 and 24, with up to 2 decimal places? The numbers should range from 1 to 24, as well as include decimals like 1.00, 1.01, 1.02, all the way up to 24.99. ...

What is the best way to incorporate "thread.sleep" in an Angular 7 app within a non-async method like ngOnInit()?

Despite the numerous questions and solutions available on Stack Overflow, none of them seem to work when called from a component's init function that is not asynchronous. Here's an example: private delay(ms: number) { return new Promise( ...