如何将文件从Angular 2发送到API

时间:2017-09-26 12:34:14

标签: javascript angular typescript asp.net-web-api

我的页面中有以下代码,并尝试从WEB API上传文件。我试过将formData中的文件数据传递给WEB API,但我不知道如何读取在formData中发送的文件。

如何将文件从angular API发送到WEB API,如何在API中阅读?

Angular2前端部分

<input #fileInput type="file"/>
<button (click)="addFile()">Add</button>

Angular2组件

@ViewChild("fileInput") fileInput;

addFile(): void {
    let fi = this.fileInput.nativeElement;
    if (fi.files && fi.files[0]) {
        let fileToUpload = fi.files[0];
        this.uploadService
            .upload(fileToUpload)
            .subscribe(res => {
                console.log(res);
            });
    }
}

Angular2上传服务

upload(fileToUpload: any) {
 
// var input =?? ; How can I send files to WEBAPI controller action.
    return this.http
        .post("/api/uploadFile", input);
}

WEB API

[HttpPost]
    public string uploadFile()
    {
   // How can I handle files which are sent from UI
        return "uploaded";
    }

1 个答案:

答案 0 :(得分:0)

在前端,我们发送文件:

this.uploadService
    .upload(theFile)
    .subscribe(
        res => console.log('Uploaded file with content:', res),
        err => console.error('Failed with error:', error)
    );

在服务中:

upload(fileToUpload) {
    return this.http.post('api/file/endpoint',
        fileToUpload,
        new HttpHeaders().set('Content-Type', 'application/octet-stream')
    )
    .map(res => res.text()); //mapping to text just to see the string response propagated to component subscribe
}

ASP.NET控制器

[Route("api/file/endpoint")]
[HttpPost]
public string GetFile()
{
    using (var stream = new StreamReader(Request.Body))
    {
        return stream.ReadToEnd();
    }
}

当然,您可以使用其他方式来处理流,包括异步流。