使用Asp.Net Core Web API文件上传文件始终为null

Acj*_*cjb 6 asp.net asp.net-core-webapi angular

我正在使用带有ASP.NET核心Web API的Angular 2来实现文件上传来处理请求.

我的HTML代码如下:

<input #fileInput type="file"/>
<button (click)="addFile()">Add</button>
Run Code Online (Sandbox Code Playgroud)

和angular2代码

addFile(): void {
    let fi = this.fileInput.nativeElement;
    if (fi.files && fi.files[0]) {
        let fileToUpload = fi.files[0];
        this.documentService
            .uploadFile(fileToUpload)
            .subscribe(res => {
                console.log(res);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

和服务看起来像

public uploadFile(file: any): Observable<any> {
    let input = new FormData();
    input.append("file", file, file.name);
    let headers = new Headers();
    headers.append('Content-Type', 'multipart/form-data');
    let options = new RequestOptions({ headers: headers });
    return this.http.post(`/api/document/Upload`, input, options);
}
Run Code Online (Sandbox Code Playgroud)

和控制器代码

[HttpPost]
public async Task Upload(IFormFile file)
{
    if (file == null) throw new Exception("File is null");
    if (file.Length == 0) throw new Exception("File is empty");

    using (Stream stream = file.OpenReadStream())
    {
        using (var binaryReader = new BinaryReader(stream))
        {
            var fileContent = binaryReader.ReadBytes((int)file.Length);
            //await this.UploadFile(file.ContentDisposition);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的RequestHeader看起来像

POST /shell/api/document/Upload HTTP/1.1
Host: localhost:10050
Connection: keep-alive
Content-Length: 2
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJDb3JyZWxhdGlvbklkIjoiZDZlNzE0OTUtZTM2MS00YTkxLWExNWUtNTc5ODY5NjhjNDkxIiwiVXNlcklkIjoiMSIsIlVzZXJOYW1lIjoiWjk5OTkiLCJXb3Jrc3BhY2UiOiJRc3lzVFRAU09BVEVNUCIsIk1hbmRhbnRJZCI6IjUwMDEiLCJDb3N0Q2VudGVySWQiOiIxMDAxIiwiTGFuZ3VhZ2VDb2RlIjoiMSIsIkxhbmd1YWdlU3RyaW5nIjoiZGUtREUiLCJTdGF0aW9uSWQiOiI1NTAwMSIsIk5hbWUiOiJJQlMtU0VSVklDRSIsImlzcyI6InNlbGYiLCJhdWQiOiJodHRwOi8vd3d3LmV4YW1wbGUuY29tIiwiZXhwIjoxNDk1Mzc4Nzg4LCJuYmYiOjE0OTUzNzUxODh9.5ZP7YkEJ2GcWX9ce-kLaWJ79P4d2iCgePKLqMaCe-4A
Origin: http://localhost:10050
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Content-Type: multipart/form-data
Accept: application/json, text/plain, */*
Referer: http://localhost:10050/fmea/1064001/content
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Run Code Online (Sandbox Code Playgroud)

我面临的问题是控制器中的文件始终为null.

请有人帮助我搞清楚这个问题.

提前致谢.

cod*_*ter 15

您不需要对FormData使用'multipart/form-data'

在Angular 2组件中:

<input type="file" class="form-control" name="documents" (change)="onFileChange($event)" />

onFileChange(event: any) {
    let fi = event.srcElement;
    if (fi.files && fi.files[0]) {
        let fileToUpload = fi.files[0];

        let formData:FormData = new FormData();
         formData.append(fileToUpload.name, fileToUpload);

        let headers = new Headers();
        headers.append('Accept', 'application/json');
        // DON'T SET THE Content-Type to multipart/form-data, You'll get the Missing content-type boundary error
        let options = new RequestOptions({ headers: headers });

        this.http.post(this.baseUrl + "upload/", formData, options)
                 .subscribe(r => console.log(r));
    }
}
Run Code Online (Sandbox Code Playgroud)

在API方面

[HttpPost("upload")]
public async Task<IActionResult> Upload()
{
    var files = Request.Form.Files;

    foreach (var file in files)
    {
       // to do save
    }

    return Ok();
}
Run Code Online (Sandbox Code Playgroud)


Sch*_*aga 6

更新:经过ASP.NET Core团队的澄清后,它与Startup该类中的compat开关有关。如果您这样设置:

services
    .AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
Run Code Online (Sandbox Code Playgroud)

那么,如果您还[FromForm]从文件参数中删除属性,就可以了。

旧帖子:我遇到了与最新的ASP.NET Core WebApi(在撰写本文时为2.1.2)类似的问题,只有经过一个小时的堆栈溢出,研究以及大量的试验和错误后,我才能偶然解决。我从这样的Angular 6应用程序发布了文件:

const formData: FormData = new FormData();
formData.append('file', file, file.name);

const req = new HttpRequest('POST', 'upload-url', formData, {
    reportProgress: true
});

this.http.request(req).subscribe(...) // omitted the rest
Run Code Online (Sandbox Code Playgroud)

问题在于,即使将IFormFile fileAction方法参数null放在[FromForm]最前面也总是如此。[FromForm]由于ASP.NET Core 2.1中的api控制器行为发生了更改,因此成为必需,该位置[FromBody]成为api控制器的默认设置。奇怪的是,它仍然没有起作用,价值仍然存在null

我终于通过使用属性明确说明表单内容参数的名称来解决了该问题,如下所示:

public async Task<IActionResult> UploadLogo([FromForm(Name = "file")] IFormFile file)        
{
     ...
}
Run Code Online (Sandbox Code Playgroud)

现在,文件上传已正确绑定到控制器参数。我希望这会在将来对某人有所帮助,因为这几乎使我失去理智:D