Por ejemplo, creé una carpeta llamada 'cargar' en la carpeta src.
archivo HTML:
<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>archivo upload-modal.component.ts
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")); } } } cuando hago clic en el botón de carga, y encontré este error en el registro de la consola = http://localhost:3000/upload 404 (Not Found)
Supongo que esto debe tener que ver con el enrutamiento. Alguien tiene experiencia antes?
Espero que esto ayude: con el código completo.
necesita ejecutar este cmd: npm i ng2-file-upload --save
Código: https://github.com/valor-software/ng2-file-upload
Demostración: http://valor-software.com/ng2-file-upload/
Podrías hacerlo de esta manera:
//in html <input type="file" (click)="handleFileInput($event.target.value)"> //in .ts file handleFileInput(file: FileList) { this.fileToUpload = file.item(0); } puede agregar this.fileToUpload a formdata .