Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload and download in angular 4 typescript

How can I download (.exe file which is in root path) and Upload a file from Angular 4?
I am new to Angular4 and typescript and .NET Core Web API.

I have googled for this but could not find the solution.

Here are some similar questions that I found:

  • Uploading file to controller using typescript

  • Returning binary file from controller in ASP.NET Web API

like image 693
Victor Athoti. Avatar asked Jul 18 '17 08:07

Victor Athoti.


5 Answers

I'd like to add an Angular 4.3/5/6/7/8 update for this especially vis-a-vis the simplified HttpClient. The absence of the 'Content-Type' is especially important since Angular automatically constructs the Content-Type (there is a propensity to add Content-Type=undefined. Don't, as it will create issues under various circumstances and, perhaps, not good practice either). Once there is no Content-Type, the browser will automatically add 'multipart/form-data' and associated parameters. Note, the backend here is Spring Boot although it shouldn't matter.

Here's some pseudo code--please excuse phat fingers. Hope this helps:

MyFileUploadComponent(.html):

...
<input type="file" (change)=fileEvent($event)...>

MyFileUploadComponent(.ts) calls MyFileUploadService(.ts) on fileEvent:

...
public fileEvent($event) {
   const fileSelected: File = $event.target.files[0];
   this.myFileUploadService.uploadFile(fileSelected)
   .subscribe( (response) => {
      console.log('set any success actions...');
      return response;
    },
     (error) => {
       console.log('set any error actions...');
     });
}

MyFileUploadService.ts:

...
public uploadFile(fileToUpload: File) {
  const _formData = new FormData();
  _formData.append('file', fileToUpload, fileToUpload.name);   
  return<any>post(UrlFileUpload, _formData); 
  //note: no HttpHeaders passed as 3rd param to POST!
  //So no Content-Type constructed manually.
  //Angular 4.x-6.x does it automatically.
}
  
like image 164
MoMo Avatar answered Nov 14 '22 13:11

MoMo


For uploading file, we can post data in form of multipart/form-data. For that, we have to use the FormData class. Here is an example.

Template:

<form #yourForm="ngForm" (ngSubmit)="onSubmit()">
      <input type="text" [(ngModel)]="Name" name="Name"/>
      <input type="file" #fileupload [(ngModel)]="myFile" name="myFile" (change)="fileChange(fileupload.files)"/>
      <button type="submit">Submit</button>
</form>

Component:

import { Http, Response, Headers, RequestOptions } from '@angular/http';
/* When we select file */
Name:string; 
myFile:File; /* property of File type */
fileChange(files: any){
    console.log(files);

    this.myFile = files[0].nativeElement;
}

/* Now send your form using FormData */
onSubmit(): void {
    let _formData = new FormData();
    _formData.append("Name", this.Name);
    _formData.append("MyFile", this.myFile);
    let body = this._formData;
    let headers = new Headers();
    let options = new Options({
        headers: headers
    });
    this._http.post("http://example/api/YourAction", body, options)
      .map((response:Response) => <string>response.json())
      .subscribe((data) => this.message = data);
}

For API to upload file, see this:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2

like image 29
Mohnish Karhade Avatar answered Nov 14 '22 14:11

Mohnish Karhade


its very simple component.html will look like

<div class="form-group col-md-6" style="margin-left:50%;margin-top:-8%" >
    <input type="file" value="upload" accept=".jpg" (change)=fileUploader($event)>
</div>

while in the ts file, it will look like

public fileUploader(event) {
    const elem = event.target;
    if (elem.files.length > 0) {
        console.log(elem.files[0]);
    }
    // ...
}
like image 2
Daniel Charles Mwangila Avatar answered Nov 14 '22 15:11

Daniel Charles Mwangila


<form [formGroup]="uploadForm" (ngSubmit)="onSubmit()">
    Select image to upload:
    <input type="file" name="avatar" id="fileToUpload" formControlName="file1" (change)="fileEvent($event)">
    <input type="submit" value="Upload Image" name="submit">
</form>
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-praveen',
  templateUrl: './praveen.component.html',
  styleUrls: ['./praveen.component.css']
})
export class PraveenComponent implements OnInit {

  constructor(private httpClient:HttpClient) { }
    uploadForm = new FormGroup ({
        file1: new FormControl()
    });
    filedata:any;
    fileEvent(e){
        this.filedata=e.target.files[0];
        console.log(e);
    }
    onSubmit() {
        let formdata = new FormData();
        console.log(this.uploadForm)
        formdata.append("avatar",this.filedata);
        this.httpClient
        .post<any>("http://localhost:3040/uploading",formdata)
        .subscribe((res)=>{console.log(res});
    }
  ngOnInit() {
  }

}
like image 1
Praveen Gubbala Avatar answered Nov 14 '22 15:11

Praveen Gubbala


to download file with angular try with this, it works`

download(row) {
    return this.Http
      .get(file_path , {
        responseType: ResponseContentType.Blob,
      })
      .map(res => {
        return {
          filename: row.name,
          data: res.blob()
        };
      })
      .subscribe(res => {
        let url = window.URL.createObjectURL(res.data);
        let a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display: none');
        a.href = url;
        a.download = res.filename;
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();
      });
  }

`

like image 1
achref akrouti Avatar answered Nov 14 '22 14:11

achref akrouti