Home  >  Article  >  Web Front-end  >  Solving the problem of Angular image upload preview path

Solving the problem of Angular image upload preview path

php中世界最好的语言
php中世界最好的语言Original
2018-04-13 15:09:212119browse

This time I will bring you AngularPictureUploadSolution to the preview path problem, and Notesto solve the problem of Angular picture upload preview path Which ones, the following are practical cases, let’s take a look.

Preface

When working on a project some time ago, I encountered a problem that AngularJS implements the function of image preview and upload. In Angular4, when uploading and selecting a local preview of an image through input:file, window.URL.createObjectURL There is an error in assigning the obtained url to the src of the image:

WARNING: sanitizing unsafe URL value

The following introduces 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 interpolationexpression 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 through the bypassSecurityTrustUrl method of santizer into a security path.

Finally, assign the generated secure url to imgUrl. Now there will be no problem~

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

AngularJS implements price calculation function

How Webpack builds Electron applications

The above is the detailed content of Solving the problem of Angular image upload preview path. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn