将文件从Angular 5/6上传到WebApi C#

时间:2018-10-03 09:21:28

标签: asp.net angular typescript file-upload

我需要将文件转换为字节数组并放入WebApi

我的HTML模板:

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

结束我的组件:

    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);        
    }

在此示例中,不使用服务

1 个答案:

答案 0 :(得分:-1)

需要创建一个FormData对象来上传图像

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));        
}