'Angular 2 - How to upload file and store in local folder

For example, I created a folder called 'upload' under src folder.

html file:

<div>
   <input type="file" id="photo" (change)="onChange($event)" />
</div>
<div class="col-md-6 mb-4 mt-3">
   <button (click)="upload()" class="btn btn-primary w-100">Upload Picture</button>
</div>

upload-modal.component.ts file

import { Http, Response } from '@angular/http';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import "rxjs/add/operator/do";
import "rxjs/add/operator/map";
const uploadURL = '/upload';

@Component({

selector: 'upload-modal',
templateUrl: './upload-modal.component.html',
styleUrls: ['./upload-modal.component.css']
})
export class UploadModalComponent {
displayMessage: string = '';
constructor(public activeModal: NgbActiveModal, private http: Http, private el: ElementRef) { }
setDisplayMessage(msg: string) {
   this.displayMessage = msg;
 }

upload() {
   this.activeModal.dismiss('Cross click');
 }

onChange(event) {
 let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#photo');

let fileCount: number = inputEl.files.length;

let formData = new FormData();

if (fileCount > 0) { // a file was selected

  formData.append('photo', inputEl.files.item(0));

  this.http
    .post(uploadURL, formData).map((res: Response) => res.json()).subscribe(
    // map the success function and alert the response
    (success) => {
      alert("success");
    },
    (error) => alert("error"));
   }

  }
}

when I click upload button, and I found this error in console log= http://localhost:3000/upload 404 (Not Found)
I guess this must to do with routing. Anyone has experience before?



Solution 1:[1]

hope this helps: with complete code.

you need to run this cmd: npm i ng2-file-upload --save

Code: https://github.com/valor-software/ng2-file-upload

Demo: http://valor-software.com/ng2-file-upload/

Solution 2:[2]

You could do it this way:

//in html
<input type="file" (click)="handleFileInput($event.target.value)">

//in .ts file
handleFileInput(file: FileList) {
    this.fileToUpload = file.item(0);
}

you can append this.fileToUpload to formdata.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tk1993
Solution 2 jwpfox