Reputation: 1573
As part of our application we would like to preview the files the users are uploading, before they are actually available on the server. To do this I have tried a couple of things:
URL.createObjectURL()
, gives WARNING: sanitizing unsafe style value blob:http://localhost:4200/16db9654-3119-4d55-9b59-715c2d31b334 (see http://g.co/ng/security#xss).
url()
around the blob url: WARNING: sanitizing unsafe style value url(blob:http://localhost:4200/86da46b1-5431-46d0-8757-13c75e09abc2) (see http://g.co/ng/security#xss).
ERROR Error: Required a safe Style, got a URL
url()
around the sanitized value in the template WARNING: sanitizing unsafe style value url(SafeValue must use [property]=binding: blob:http://localhost:4200/72561f3d-0ff7-435b-8ac9-ec3a7c0cfbb0 (see http://g.co/ng/security#xss)) (see http://g.co/ng/security#xss).
url()
around the blob url before sanitizing ERROR Error: Required a safe Style, got a URL
And during none of these the background image actually appeared. I checked the dom using the chrome inspecter, and in none of the cases did the attribute actually get set.
So what is the correct way of doing this? I have a File instance at start.
Upvotes: 3
Views: 9003
Reputation: 1339
HTML:
<input type='file' (change)="onAdd($event)">
<div class="col-4 col-sm-4 col-md-4 col-lg-4 col-xl-4" *ngIf="url">
<img [src]="url">
</div>
Type Script:
onAdd(event: any) {
console.log(event);
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event: any) => {
this.slika = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
}
EDIT:
Change your code to this:
public addFile(event: any) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event: any) => {
this.url = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
}
and this:
<input type="file" (change)="addFile($event)">
With these changes it should work now.
Upvotes: 11