File upload and download in angular 4 typescript

后端 未结 7 1770
一个人的身影
一个人的身影 2020-12-13 10:58

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 h

相关标签:
7条回答
  • 2020-12-13 11:28

    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.
    }
      
    
    0 讨论(0)
提交回复
热议问题