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

434
Vistas
File upload in Angular2 not working

I am trying to create a file upload functionality where an user can upload geotiff (could be of several GBs in size). For some reason my angular code is not able to hit the api and throws 404 but I am able to upload file with Postman.

Angular Code:

 fileChange(event) {
        let token = localStorage.getItem('userToken');
        let fileList: FileList = event.target.files;
        if (fileList.length > 0) {
            let file: File = fileList[0];
            let formData: FormData = new FormData();
            formData.append('files', file, file.name);
            let headers = new Headers();
            headers.append('Content-Type', 'multipart/form-data');
            headers.append("Authorization", token);
            let options = new RequestOptions({ headers: headers });
            this.uploadInProgress = true;
            this._http.post(`${this.uploadApiUrl}`, formData, options)
                .map(res => res.json())
                .catch(error => Observable.throw(error))
                .subscribe(
                data => console.log('success'),
                error => console.log(error),
                () => this.uploadInProgress = false)
        }
    }

API:

// POST: api/GeoTif
[HttpPost]
public async Task<IActionResult> Post(List<IFormFile> files)
        {
            long size = files.Sum(f => f.Length);


            return Ok(new { NoOfUploadedFileCount = files.Count, TotalFileSize =size });
        }
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

I understand that there is an issue with the HTTP service and FormData.. you can use XMLHttpRequest to accomplish it:

fileChange(event: Event) {
    this.uploadFile(event)
        .subscribe(() => {
            console.log('sent');
        })
}

private uploadFile(event: Event) {
    return Observable.create(observer => {
        const token = localStorage.getItem('userToken');
        const fileList = event.target.files;
        if (fileList.length > 0) {
            const file = fileList[0];
            const formData = new FormData();
            const xhr = new XMLHttpRequest();

            formData.append('files', file, file.name);
            this.uploadInProgress = true;
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        observer.next(JSON.parse(xhr.response));
                        observer.complete();
                    } else {
                        observer.error(xhr.response);
                    }
                    this.uploadInProgress = false;
                }
            }

            xhr.open('POST', this.uploadApiUrl, true);
            xhr.send(formData);
        }
    });
}
over 4 years ago · Santiago Trujillo Denunciar

0

Add your URL with http:// (Ex: http://localhost/api/GeoTif/). And remove the following code.

headers.append('Content-Type', 'multipart/form-data');
headers.append("Authorization", token);
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