Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

264
Vistas
Cómo subir un archivo en Angular2

Tengo que enviar un formulario junto con la imagen. Probé este código (con varias formas) pero no funcionó para mí. ¿Hay alguien que tenga una demostración funcional de la carga de archivos usando angular2? Por favor, ayúdame.

componente.html

 <form class="form-horizontal" role="form" > <div class="form-group"> <label class="control-label col-sm-4" for="myname" style="">Name<span class="asterisk">*</span></label> <div class="col-sm-7"> <div> <input type="text" class="form-control" id="myname" [(ngModel)]="myfile.name"> </div> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="myimage">Image</label> <div class="col-sm-7"> <div> <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." /> </div> </div> </div> <div class="form-group"> <div class="text-center"> <button type="button" (click)="upload()">Upload</button> </div> </div> </form>

componente.ts

 myfile={ "name":"Mubashshir", "image":'' } fileChangeEvent(fileInput: any){ this.myfile.image = fileInput.target.files; } upload(){ this.base_path_service.PostRequest('http://128.199.190.109/api/school/schoolDetail/',this.myfile) .subscribe( data => { console.log("data submitted"); }, err => console.log(err), () =>{ console.log('Authentication Complete'); } ); }
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

De hecho, la clase Http no admite eso en este momento.

Debe aprovechar el objeto XHR subyacente para hacer eso:

 import {Injectable} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; @Injectable() export class UploadService { constructor () { this.progress$ = Observable.create(observer => { this.progressObserver = observer }).share(); } private makeFileRequest (url: string, params: string[], files: File[]): Observable { return Observable.create(observer => { let formData: FormData = new FormData(), xhr: XMLHttpRequest = new XMLHttpRequest(); for (let i = 0; i < files.length; i++) { formData.append("uploads[]", files[i], files[i].name); } xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { observer.next(JSON.parse(xhr.response)); observer.complete(); } else { observer.error(xhr.response); } } }; xhr.upload.onprogress = (event) => { this.progress = Math.round(event.loaded / event.total * 100); this.progressObserver.next(this.progress); }; xhr.open('POST', url, true); xhr.send(formData); }); } }

Consulte este plunkr para obtener más detalles: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info .

Hay un problema y un PR pendiente con respecto a esto en el repositorio de Angular:

  • https://github.com/angular/angular/issues/10424
  • https://github.com/angular/angular/pull/7310/files
over 4 years ago · Santiago Trujillo Denunciar

0

su archivo de servicio http:

 import { Injectable } from "@angular/core"; import { ActivatedRoute, Router } from '@angular/router'; import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http"; import {Observable} from 'rxjs/Rx'; import { Constants } from './constants'; declare var $: any; @Injectable() export class HttpClient { requestUrl: string; responseData: any; handleError: any; constructor(private router: Router, private http: Http, private constants: Constants, ) { this.http = http; } postWithFile (url: string, postData: any, files: File[]) { let headers = new Headers(); let formData:FormData = new FormData(); formData.append('files', files[0], files[0].name); // For multiple files // for (let i = 0; i < files.length; i++) { // formData.append(`files[]`, files[i], files[i].name); // } if(postData !=="" && postData !== undefined && postData !==null){ for (var property in postData) { if (postData.hasOwnProperty(property)) { formData.append(property, postData[property]); } } } var returnReponse = new Promise((resolve, reject) => { this.http.post(this.constants.root_dir + url, formData, { headers: headers }).subscribe( res => { this.responseData = res.json(); resolve(this.responseData); }, error => { this.router.navigate(['/login']); reject(error); } ); }); return returnReponse; } }

llame a su función (archivo de componente):

 onChange(event) { let file = event.srcElement.files; let postData = {field1:"field1", field2:"field2"}; // Put your form data variable. This is only example. this._service.postWithFile(this.baseUrl + "add-update",postData,file).then(result => { console.log(result); }); }

su código html:

 <input type="file" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="stock.documents" #documents="ngModel">
over 4 years ago · Santiago Trujillo Denunciar

0

Método onChange() mejorado:

 file: File; onChange(event: EventTarget) { let eventObj: MSInputMethodContext = <MSInputMethodContext> event; let target: HTMLInputElement = <HTMLInputElement> eventObj.target; let files: FileList = target.files; this.file = files[0]; console.log(this.file); }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda