Angular2到Asp.net核心Webapi IFormFile为空

时间:2017-03-13 03:28:59

标签: asp.net-web-api

我正在使用带有asp.net核心webapi的angular2。使用以下代码发送文件信息。 IFormFile始终为null。我在post输入和api方法参数中使用了相同的名字,仍然没有运气。请帮帮我。

FORMDATA

 this.formData.append("file", f,f.name);

组件方法

public UploadFiles() {
        console.log("Form Data:" + this.formData);

        let saved: boolean = false;
        this.claimsService
            .UploadFiles(this.formData)
            .subscribe(data => {
                saved = data;
            }, error => {
                console.log(error)
                swal(error);

            })
    }

服务方法

UploadFiles(data: FormData): Observable<boolean> {
        return this.ExecuteFilePost("Upload/Upload", data);
    }

基本服务方式:

public ExecuteFilePost(action: string, data: FormData) {
        let _body = data;

        let headers = new Headers({ 'Content-Type': undefined});

        let url = this._baseUrl + action;

        let requestoptions: RequestOptions = new RequestOptions({
            headers: headers,
        });

        console.log('req url:' + url);
        return this.http.post(url,_body,requestoptions)
            .share()
            .map((res: Response) => {
                if (res.status < 200 || res.status >= 300) {
                    throw new Error('This request has failed ' + res.status);
                }
                else {
                    return res.json();
                }
            });

    }

WebApi方法

[HttpPost]
        [ActionName("Upload")]
        public async Task Upload(IFormFile file)
        {

            var uploads = Path.Combine(_environment.WebRootPath, "uploads");
           // foreach (var file in files)
           // {
                if (file.Length > 0)
                {
                    using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                }
           // }
        }

Chrome请求屏幕 enter image description here

1 个答案:

答案 0 :(得分:0)

我知道这篇文章很老,但也许对其他人而言。你可以这样做:

HTML:

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

组件:

@ViewChild("fileInput") fileInput;

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

服务:

upload(files: any) {
        let formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append("files", files[i]);
        }

        return this.http
            .post(fileUploadApi, formData)
            .map(response => this.extractData(response as Response))
            .catch(error => this.httpErrorHandlerService.responseError(error));
    }

Web API

[HttpPost]
        [Route("Upload")]
        public IActionResult UploadFiless([FromForm] IFormFileCollection files)
        {
            try
            {
                return this.Ok();
            }
            catch (Exception)
            {
                return this.BadRequest();
            }
        }