What steps should I take to address the issue of sanitizing a potentially harmful URL value that contains a

I've encountered a URL sanitization error in Angular and despite researching various solutions, I have been unable to implement any of them successfully in my specific case. Hence, I am reaching out for assistance.

Below is the function causing the issue:

@Input()
    maxFileSize: number = 1000000;

    public fileChangeEvent(fileInput: any) {
        if (fileInput.target.files && fileInput.target.files[0]) {
            const reader = new FileReader();
            reader.onload = (e: any) => {
                if (e.target.result) {
                    if (e.target.result.length < this.maxFileSize) {
                        this.value = e.target.result;
                    } else {
                        alert(`Logo size ${e.target.result.length} cannot exceed ${this.maxFileSize} bytes.`);
                    }
                }
            };

            reader.readAsDataURL(fileInput.target.files[0]);
        }
    }

I attempted to use this.sanitizer.bypassSecurityTrustUrl(url), however, since fileInput.target.files[0] is a blob in my situation, I consistently encounter an error when trying to wrap it with the sanitizer function.

This is how I'm using it in the view:

 <ng-container *ngIf="value">
        <div class="input-group-append">
            <div class="img-thumbnail">
                <img src="{{value}}" alt="Preview" />
            </div>
            <button class="btn btn-danger btn-lg" type="button" (click)="clearLogo()">
            <i class="fa fa-trash" aria-hidden="true"></i>
            Delete
            </button>
        </div>
    </ng-container>
enter code here

I also tried [src]="{{value}}", but that approach did not yield positive results either.

The error message displayed is:

WARNING: sanitizing unsafe URL value

I seek guidance on where I might be making a mistake.

Answer №1

Hopefully this solution resolves the problem for you.

initiateSanitizer(private securedSanitizer:DomSanitizer){...}
    ....
    
          const selectedFile = event.target.files[0];
          const newBlob = new Blob([selectedFile], { type: selectedFile.type });
          const newUrl = window.URL.createObjectURL(newBlob);
    
          this.result = this.securedSanitizer.bypassSecurityTrustUrl(newUrl);

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 of triggering a websocket connection event within the context of an express get request?

Having trouble incorporating WebSockets into Express's router.get request Here is the code snippet: app.js const { createServer } = require("http"); const mongoose = require('mongoose'); const config = require('./config'); const ...

Creating a function that utilizes a default argument derived from a separate argument

Consider this JavaScript function: function foo({ a, b, c = a + b }) { return c * 2; } When attempting to add type annotations in TypeScript like so: function foo({ a, b, c = a + b }: { a?: number, b?: number, c: number }): number { return c * 2; } ...

Achieving the incorporation of multiple components within a parent component using Angular 6

Within parent.component.html The HTML code I have implemented is as follows: <button type="button" class="btn btn-secondary (click)="AddComponentAdd()">Address</button> <app-addresse *ngFor="let addres of collOfAdd" [add]="addres">< ...

When trying to reload Angular 8 pages, encountering an error that reads "Cannot GET /login" and also receiving a notification stating the image '/favicon.ico' cannot be loaded due to a violation of

Encountering an issue with the error message "Cannot GET login/" appearing on the page body of my latest Angular 8 app. Despite attempting various solutions found on forums, I have been unable to resolve this error. Any suggestions or advice would be great ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

I'm having trouble with my Laravel edit page not functioning properly when using vue.js. Can anyone help me troubleshoot

Currently, I am developing a dashboard to display details. Users can click on the edit button to modify their information. However, when I try to edit by clicking the button, nothing happens. It seems like the editing feature is not functioning properly, a ...

The Highcharts xrange series is encountering the error message "x is not a function."

I am currently working in an Angular 4 (Angular-cli) environment and attempting to utilize the x-range highcharts type. After executing the npm install command npm install highcharts --save, I included these lines of code: import * as Highcharts from &ap ...

Issue encountered when attempting to establish a new loadingController with LoadingOption

Hey there, I am relatively new to Ionic and I encountered an issue while trying to create a new loading screen. Argument of type '{ content: string; }' is not assignable to parameter of type 'LoadingOptions'. Object literal may only s ...

Having trouble getting the CSS URL to work when using a leading slash?

I am attempting to utilize a background-image with a "root-relative" path like this: background-image: url("/img/bg.jpg");. In Chrome, the property is showing correctly but the image does not appear. When I change it to http://localhost:8080/img/bg.jpg, t ...

Does manipulating the context before retrieving it within a custom ContextProvider adhere to best practices?

In my React application, I have a custom ContextProvider component called RepositoryContext. This component requires a specific ID to be set inside it in order to perform CRUD operations. Here is a snippet of the code: import React, { Dispatch, PropsWithCh ...

Adding a stylesheet dynamically in Angular 2: A step-by-step guide

Is there a method to dynamically add a stylesheet URL or <style></style> in Angular2? For instance, if the variable isModalOpened is set to true, I want to apply certain CSS styles to elements outside of my root component, such as the body or ...

What is the method to display a caret in regular HTML text with the use of JavaScript?

Currently, I am studying JavaScript and aiming to develop a typing game similar to typeracer.com. The goal of the game is to type accurately and quickly without errors. In this game, users input text into a box, and JavaScript then compares their inputs w ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

Having trouble with importing a TypeScript class: encountering a "cannot resolve" error message

Could you lend me your expertise? I'm puzzled by this issue that seems to be quite simple and straightforward: export class Rectangle { height: number = 0 width: number = 0 constructor(height: number, width: number) { this. ...

What is the best way to switch between List and Grid view while automatically updating the image displayed?

**#Unique Component Implementation** import React from 'react'; import Typography from '@material-ui/core/Typography'; import Grid from '@material-ui/core/Grid'; import { makeStyles } from &apo ...

How can you transform the outcome of a TYPO3 repository search into a JSON format?

Is it possible to convert the outcome of a "findAll()" function on a Repository into a JSON object, make changes to specific properties in JavaScript, and then send it back to the Action, converting it again for use by the Action to persist it in the datab ...

Encountering an Angular 12 error 401 upon refreshing the page

Currently, I am working on a login form using angular 12 with Spring Boot that includes basic authentication spring security. When a user successfully logs in, they are directed to the main page which offers CRUD actions as depicted in the images linked be ...

Ways to update or incorporate new data within JavaScript

I'm currently experimenting with ways to incorporate additional text or even AdSense into what I believe is a .js file. There's an operational lightbox feature with a descriptive caption at the bottom, and that caption is what I want to modify. ...

What is the best way to retrieve the Axios Post response in React?

I'm facing a small issue. In my ReactJS code, I have a post function that is functioning correctly. However, I want to access the response of this function outside its scope, right where I called it. Is there a way to achieve this? async function che ...

Guide to updating information inside of script tags in html using javascript

Within my HTML, there is a script tag that looks like this: <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "VideoObject", "name": "Title", "description": "Video descrip ...