简体   繁体   中英

upload file from Angular 5/6 to WebApi c#

I need to convert a file to a byte array into my WebApi

my HTML template:

 <input style="display: none"  type="file" (change)="onFileChanged($event)" #fileInput>
 <button (click)="fileInput.click()">Select File</button>
 <button (click)="onUpload()">Upload!</button>

end my component:

    onFileChanged(event) {
      this.selectedFile = event.target.files[0]      
    }  
    onUpload() {   
      const uploadFile = new FormData();   
      uploadFile.append('string', this.selectedFile, 
                                   this.selectedFile.name);       
      this.http.post(URL ,uploadFile);        
    }

for this example not use service

Need to create a FormData object to upload the images

onUpload() {   

    let formData:FormData = new FormData();
    formData.append('uploadFile', this.selectedFile, this.selectedFile.name);
    let headers = new Headers();

    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');

    let options = new RequestOptions({ headers: headers });   

    this.http.post('http://localhost:516./....', formData, options)
     .subscribe(event =>  console.log(event));        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM