File upload and download in angular 4 typescript

后端 未结 7 1772
一个人的身影
一个人的身影 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条回答
  •  Happy的楠姐
    2020-12-13 11:13

    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:

    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) => response.json())
          .subscribe((data) => this.message = data);
    }
    

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

提交回复
热议问题