Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5: How to upload an image [duplicate]

Tags:

angular

I am using Angular 5. I have an requirement where I need to upload an image on a page and display the image?

Is there any Angular 5 tag or html tag I can do this?

I am attaching a screen shot what it look like. The user click "upload" button and there should be a pop-up where the user choose the file to upload. After they choose the file to upload and click open button. The image will appear on page?

enter image description here

Any hint or suggestion will be greatly appreciated it!!

like image 392
jadeite1000 Avatar asked Jan 19 '18 14:01

jadeite1000


1 Answers

You can use the tag from HTML:

<input type="file" name="file" id="file" (change)="onFileChanged($event)" />

and in the component:

public files: any[];

contructor() { this.files = []; }

onFileChanged(event: any) {
  this.files = event.target.files;
}

onUpload() {
  const formData = new FormData();
  for (const file of this.files) {
      formData.append(name, file, file.name);
  }
  this.http.post('url', formData).subscribe(x => ....);
}

The formData will hold the stream to your upload.

P.S. you can mark the HTML with the attribute: "multiple" and you can upload multiple data if your server can handle it.

like image 63
Samy Sammour Avatar answered Nov 10 '22 16:11

Samy Sammour