Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image preview before upload in angular 5

Tags:

I have this code to show the image preview before uploading it. However I am working with Angular 5 so I have a .ts file instead of a .js one. How can I do the same in Angular 5? I also want to show the image in all browsers.

My HTML:

<input type='file' onchange="readURL(this);"/>
<img id="blah" src="http://placehold.it/180" alt="your image"/>

My CSS:

img {
    max-width:180px;
}

input[type=file] {
    padding: 10px;
    background: #2d2d2d;
}

My JavaScript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            document.getElementById('blah').src=e.target.result
        };
        reader.readAsDataURL(input.files[0]);
    }
}
like image 291
Mrinalini Pal Avatar asked May 23 '18 07:05

Mrinalini Pal


2 Answers

.html

Update event attr and handler param for input. And you should use data binding for src attribute. Following will apply src if it's not null or undefined or hardcoded url ('http://placehold.it/180')

<input type='file' (change)="readURL($event);" />
<img id="blah" [src]="imageSrc || 'http://placehold.it/180'" alt="your image" />

.ts

In component ts file (class) you should have property imageSrc which be used in view (html) and your function should be a method of that class

...
imageSrc: string;
...
constructor(...) {...}
...
readURL(event: Event): void {
    if (event.target.files && event.target.files[0]) {
        const file = event.target.files[0];

        const reader = new FileReader();
        reader.onload = e => this.imageSrc = reader.result;

        reader.readAsDataURL(file);
    }
}
like image 193
Coffee-Tea Avatar answered Oct 25 '22 11:10

Coffee-Tea


I am using the below code to implement the image preview:

onFileChange(event: any) {
this.userFile = event.target.files[0];
this.imageSelected = this.userFile.name;
if (event.target.files && event.target.files[0]) {
  const reader = new FileReader();
  reader.onload = (e: any) => {
    this.imageSrc = e.target.result;
  };
  reader.readAsDataURL(event.target.files[0]);
}}

Which works just fine and displays the image preview. The problem I originally faced was that I receeived the below error in the chrome developer tools each time an image preview is generated:

null 404 GET Error

Everything worked fine though, there are no other errors.

If I clicked on the null:1 I was directed to the below:

null:1

After some fiddling and troubleshooting, I was able to find the solution which I have included in the edit below.

EDIT: Figured it out. I didn't have the || 'http://placehold.it/180'" included in the [src]=" on my component.html. Guess its a timing issue. Sorted now. no more error.

like image 23
fromage9747 Avatar answered Oct 25 '22 11:10

fromage9747