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

The AJAX response consistently returns a 405 status code

I am experiencing an issue with an AJAX post request. $.ajax({ type: "POST", contentType: "application/json", url: "/rating/save", data: JSON.stringify(rating), dataType: "json", mimeType: "application/json" ...

I don't understand what's happening with this ternary format in the Typescript function - something seems off

Exploring Typescript. While browsing through a project's codebase, I stumbled upon the following snippet and am unsure of its validity. Can anyone shed light on what this code is doing? It seems to be dealing with default values, but I'm not enti ...

Struggling to translate JavaScript code into Typescript

Currently in the process of converting my JavaScript code to Typescript, and encountering an error while working on the routes page stating Binding element 'allowedRoles' implicitly has an 'any' type. ProtectedRoutes.tsx const Protecte ...

Prevent rapid event triggers with a jQuery slider

I am currently working with an event function in JavaScript that involves a slider and a tooltip element. Here is the code snippet: //Hide the Tooltip initially tooltip.hide(); //Initialize the Slider slider.slider({ ...

Tips for resolving relative child routes in Angular

Routing Configuration const routes: Routes = [ { path: '', loadChildren: './home/home.module#HomeModule' }, { path: 'admin', loadChildren: './admin/admin.module#AdminModule' } ]; Nested Home Routing const ro ...

Error encountered when attempting to assign a value of the original data type within the Array.reduce function

I am in the process of developing a function that takes a boolean indicator object like this: const fruits = { apple: false, banana: false, orange: false, mango: false, }; Along with an array such as ['apple', 'orange']. The go ...

Information sent to a slot does not trigger a response

Trying to create a mobile-friendly chat app, I want to hide the new message button during conversations and use a different button on desktop. In addition, I have a dialog for creating new chat groups. <v-dialog transition="dialog-top-transition&qu ...

Encountering the error message "Attempting to access properties of undefined (specifically 'map')". Despite having the array properly declared and imported

I am facing an issue while trying to iterate through an array and display names for each person. Despite declaring the array properly, it is returning as undefined which is causing the .map function to fail. Can you help me figure out where I am making a m ...

Struggling with setting up a PHP and Ajax registration and login system

Struggling with my code and in need of assistance. Desperately trying to set up a register form where users can input their username and password to sign up. Planning to utilize ajax, however, the integration seems faulty. For testing purposes, I tried ech ...

Collaborative Desktop & Web Application powered by Javascript REST/Ajax

Currently, my node.js back-end is seamlessly working with a web-based JavaScript client by sending AJAX requests. However, I am now contemplating creating a compact desktop version of the JavaScript client using solely JavaScript, specifically leveraging ...

Am I making a mistake in my implementation of sending Socket.io messages to a designated room?

Upon a user joining, I alter their ID to a shortened random code. This change is made to utilize the id as a visible session ID on the front-end. I mention this to prevent confusion regarding non-standard socket IDs and their relation to potential issues. ...

Adding animation to rows in ngx-datatable: A Guide

I am looking to stack the rows of my data table (ngx) one after the other in a vertical fashion. I want to incorporate [@datatableAnimation], but I'm unsure where to place it. When adding it to <ngx-datatable [@datatableAnimation]>, it only af ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...

Encountering a syntax error while utilizing a JavaScript variable in a jQuery selector for a lightbox feature

I'm currently working on creating a lightbox feature and have reached the stage where I am implementing next and previous buttons to navigate through images. I am utilizing console.log to check if the correct href is being retrieved when the next butt ...

Steps to verify if a value is an integer:

Lately, I've been working on a "spinner" that increments and decrements a number by 1 each time. However, I'm struggling to add validation to the program so that it only accepts integers (no decimals). I've tried looking into NaN and parseVa ...

The process of altering the color of a table row in JavaScript can be done after dismissing a pop-up that was triggered by a button within the same row

I am tasked with changing the color of a specific table row based on user interaction. The table consists of multiple rows, each containing a button or image. When the user clicks on one of these buttons or images, a popup appears. Upon successful data sub ...

The jquery and operator fails to function

I am encountering an issue with the code snippet below. The functionality involves a button that toggles a div. Within this toggle div, there are several other divs and elements. $(function () { $('#btn').click(function (e) { e.preve ...

The process of subscribing to a service in Angular

I currently have 3 objects: - The initial component - A connection service - The secondary component When the initial component is folded/expanded, it should trigger the expansion/folding of the secondary component through the service. Within the service ...

Error class not being applied by Knockout validation

I've implemented knockout validation on a text input and the validation is working correctly. However, the errorMessageClass is not being applied to the error message. I must have made a mistake in my setup, but I can't seem to identify it. My H ...

Is there a way to launch QTP from JavaScript without relying on ActiveXObject?

Is there a way to call QTP from JavaScript without relying on ActiveXObject? I would appreciate any guidance on how to accomplish this task. Thanks in advance, Ramya. ...