This article mainly introduces to you the solution to the unsafe problem of image upload preview path in Angular4. The article introduces it in great detail through sample code. It has certain reference learning value for everyone's study or work. Friends who need it Let’s study together below.
Preface
When I was working on a project some time ago, I encountered a problem with AngularJS’s ability to implement image preview and upload. In Angular4, When uploading the selected image for local preview through input:file
, an error occurs when assigning the url obtained through window.URL.createObjectURL
to the src of the image:
WARNING: sanitizing unsafe URL value
The following is the solution:
html code:
<input type="file" (change)="fileChange($event)" > <img [src]="imgUrl" alt="">
Among them, the change method will be called after each image is selected. The src of the image must be in the form of attribute binding. Using interpolation expressions will also cause errors.
ts code
import { Component, OnInit } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser' @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { imgUrl; constructor( private sanitizer: DomSanitizer ){} ngOnInit() { } fileChange(event){ let file = event.target.files[0]; let imgUrl = window.URL.createObjectURL(file); let sanitizerUrl = this.sanitizer.bypassSecurityTrustUrl(imgUrl); this.imgUrl = sanitizerUrl; } }
First, introduce DomSanitizer, and then inject it into the constructor. The most important thing is to convert the imgUrl generated by window.URL.createObjectURL
into a safe path through the bypassSecurityTrustUrl method of santizer. .
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How vue springboot implements single sign-on cross-domain issues (detailed tutorial)
Detailed introduction to commonly used tools in javascript Class encapsulation (detailed tutorial)
Detailed introduction to the source code entry file in vue (detailed tutorial)
Detailed introduction to several JavaScript coding specifications (Detailed tutorial)
How to implement the drag verification code function using jQuery and vue
How to implement the email prompt completion function in JS
The above is the detailed content of Problems with unsafe image paths when using Angular4. For more information, please follow other related articles on the PHP Chinese website!