1

I created a Angular2 app that allows the user to upload images. I want to implement a preview option. However, when i try to imperilment it the image doesn't show up. How do i achieve this feature?

UploadComponent.ts

import * as ng from '@angular/core';
//import { UPLOAD_DIRECTIVES } from 'ng2-uploader';
import {UploadService} from '../services/upload.service'; 

@ng.Component({
  selector: 'my-upload',
  providers:[UploadService], 
  template: require('./upload.html')
})
export class UploadComponent {
    progress:any; 
    logo:any; 
    filesToUpload: Array<File>;
    constructor(public us:UploadService){
        this.filesToUpload = [];
    }
    upload() {
        this.us.makeFileRequest("http://localhost:5000/api/SampleData/Upload", this.filesToUpload)
        .then((result) => {
            console.log(result);
        }, (error) => {
            console.error(error);
        });
    }
    onFileChange(fileInput: any){
        this.logo = fileInput.target.files[0];
    }
}

Upload.html

<h2>Upload</h2>
<input type="file" (change)="onFileChange($event)" placeholder="Upload image..." />
<button type="button" (click)="upload()">Upload</button>
 <img [src]="logo" alt="Preivew"> 

3 Answers 3

9

The way you try it, you don't get the image URL with fileInput.target.files[0], but an object.

To get an image URL, you can use FileReader (documentation here)

onFileChange(fileInput: any){
    this.logo = fileInput.target.files[0];

    let reader = new FileReader();

    reader.onload = (e: any) => {
        this.logo = e.target.result;
    }

    reader.readAsDataURL(fileInput.target.files[0]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yup that explains why i kept seeing the fileReader on other peoples code. Thanks!
Can i leave change it to reader.readAsDataURL(this.logo); instead of reader.readAsDataURL(fileInput.target.files[0]); ? Or will this produce an error?
1

  
  filesToUpload: Array<File> = [];
  url: any;
  image: any;
  
//file change event 
  
  filechange(fileInput: any) {

    this.filesToUpload = <Array<File>>fileInput.target.files;
    this.image = fileInput.target.files[0]['name'];
    this.readurl_file(event);
  }
  
//read url of the file
  
  readurl_file(event) {
    if (event.target.files && event.target.files[0]) {
      const reader = new FileReader();
      reader.onload = (eve: any) => {
        this.url = eve.target.result;
      };
      reader.readAsDataURL(event.target.files[0]);
    }
  }
  
   
   <div  class="form-group">
      <label for="image">Image</label>
      <input type="file"  class="form-control"  (change)="filechange($event)" placeholder="Upload file..." >
    </div>
    <div class="container">
        <img [src]="url">
    </div>
  
  

Comments

0

Using FileReader is not a good practice. If an image is too large it can crash your browser because onload function load whole image in RAM.

Better approach is to use:

url = URL.createObjectURL($event.target.files[0]);

Then, show it out with DomSanitizer:

this.sanitizer.bypassSecurityTrustUrl(url)

So in ts:

constructor(private sanitizer: DomSanitizer) {} 

onFileChange(fileInput: any){
    this.url = URL.createObjectURL($event.target.files[0]);
}

get previewUrl(): SafeUrl {
   return this.sanitizer.bypassSecurityTrustUrl(this.url);
}

And in html:

<img [src]="previewUrl"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.