c# - 尝试上传具有 Angular 2 的文档时,Web API 中的文件计数始终为零

标签 c# angular file asp.net-web-api file-upload

我正在尝试使用 C# 中的 Web API 上传文件。为此,我使用的代码如下。 当我尝试上传文档时,httpRequest.Files.Count 值始终为零。 我做错了什么?

mcDocuments.ts 文件

fileChange(event) {
  debugger;
  let fileList: FileList = event.target.files;
  if (fileList.length > 0) {
    let file: File = fileList[0];
    let formData: FormData = new FormData();
    formData.append('uploadFile', file, file.name);
    let token = JSON.parse(Cookie.get('currentUser')).token
    let headers = new Headers();
    headers.append('Access-Control-Allow-Origin', '*');

    headers.append('Authorization', 'bearer ' + token);

    headers.append('UserName',
      JSON.parse(Cookie.get('currentUser')).username);
    headers.append('Content-Type', 'multipart/form-data');

    let options = new RequestOptions({ headers: headers });
    let apiUrl1 = "http://localhost:53732/api/UploadFileApi";
    this.http.post(apiUrl1, formData, options)
      .map(res => res.json())
      .catch(error => Observable.throw(error))
      .subscribe(
      data => console.log('success'),
      error => console.log(error)
      )
  }
  window.location.reload();
}

mcDocuments.html 文件

  <input type="file" id="btnUpload" value="Upload" (change)="fileChange($event)" class="upload" /> 

网络 API

  using System.Net.Http;
  using System.Web;
  using System.Web.Http;
  namespace FileUpload_WebAPI_Angular2.Controllers
  {
  public class UploadFileApiController : ApiController
  {
    [HttpPost]
    public HttpResponseMessage UploadJsonFile()
    {
        HttpResponseMessage response = new HttpResponseMessage();
        var httpRequest = HttpContext.Current.Request;

        if (httpRequest.Files.Count > 0)
        {
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var filePath = 
                HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
                postedFile.SaveAs(filePath);
            }
           }
        return response;
       }
     }
   }

module.ts 文件

   declarations: [    McDocumentsComponent,],
   providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
   bootstrap: [McDocumentsComponent]

最佳答案

检查您的拦截器类是否设置了内容类型。如果是这样,请将其删除。

关于c# - 尝试上传具有 Angular 2 的文档时,Web API 中的文件计数始终为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46335480/

相关文章:

Android 3.x+ Java ZipFile 类 - 无法从大文件中读取 ZipEntries

c# - 如何检测是否安装了 Microsoft Edge?

c# - 如何使用 Spreadsheetgear 为 Excel 中的单元格添加数据验证 - C# .NET

javascript - 利用 Angular 中的导入函数进行插值

node.js - Angular/TypeScript 编译的初学者问题

java - 如何更新由 openFileOutput 创建的文件

c# - WebAPI POST 方法抛出空异常

c# - 中继访问被拒绝 5.7.1

angular - Karma 单元测试/STORE - 状态未定义

file - TVOS FileManager 的 createFile 失败并出现错误 1