使用 Angular 6 将文件上传到 Web Api C#

Sar*_*van 3 c# httpclient asp.net-web-api angular netcoreapp2.1

我有 Angular CLI 应用程序和 Dot net core 2.0 Web API。我需要将文件从 Angular 上传到 Web API。从 Web API 到服务器。当我使用 Http 时它工作正常。使用 HttpClient 时,它不起作用。这是我的 component.ts 代码:

fileChange(event, grdvalue) {
debugger;
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
  let file: File = fileList[0];
  const formData: FormData = new FormData();
  let GridName = grdvalue;

  formData.append('file', file, file.name);
  formData.append('Id', this.userId);
  formData.append('GridValue', GridName)

  this.myService.PostFileToAzure(formData).subscribe(details => {
    debugger;
  },
    (error) => {
      debugger;
    })
  }
 }
Run Code Online (Sandbox Code Playgroud)

这是我的服务代码:

 PostFileToAzure(form) {
    debugger;
    var body = JSON.stringify(form);
    return this.http.post(this.baseApiURL + '/Interpretation/InterpreterFileUpload', form);
}
Run Code Online (Sandbox Code Playgroud)

这是我的 Web API 代码:

[HttpPost("InterpreterFileUpload")]
    public async Task<IActionResult> InterpreterFileUpload()
    {
        try
        {

            var file = Request.Form.Files[0];
            HttpRequest formData = HttpContext.Request;
        }
    }
Run Code Online (Sandbox Code Playgroud)

如何使用 HttpClient 从 Angular 发送文件到 Web API。在 Web API 中出现错误,例如“内容类型不正确:应用程序/json”

Nis*_*ana 10

在角度站点使用此代码

file: any;

onSelectFile($event, file) {
    this.file = file;
  }


  uploadImage() {
    if (this.file.length === 0) {
      return;
    }

    const formData = new FormData();

    for (let file of this.file)
      formData.append(file.name, file);

    const uploadReq = new HttpRequest('POST', `api/FileUpload`, formData, {
      reportProgress: true,
    });

    this.http.request(uploadReq).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress) {
        this.progress = Math.round(100 * event.loaded / event.total);
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

这里onSelectFile应该像这样在输入上调用

<input #file type='file' multiple (change)="onSelectFile($event, file.files)">
Run Code Online (Sandbox Code Playgroud)

并在您的 asp.net 站点使用此代码

[Produces("application/json")]
    [Route("api/[controller]")]
    public class FileUploadController : Controller
    {
    private IHostingEnvironment _hostingEnvironment;

    public FileUploadController(IHostingEnvironment hostingEnvironment)
    {
      _hostingEnvironment = hostingEnvironment;
    }

    [HttpPost, DisableRequestSizeLimit]
    public ObjectResult UploadFile()
    {
      try
      {
        var file = Request.Form.Files[0];
        string folderName = "Upload";
        string webRootPath = _hostingEnvironment.WebRootPath;
        string newPath = Path.Combine(webRootPath, folderName);
        if (!Directory.Exists(newPath))
        {
          Directory.CreateDirectory(newPath);
        }
        string fileName = "";
        if (file.Length > 0)
        {
          fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
          string fullPath = Path.Combine(newPath, fileName);
          using (var stream = new FileStream(fullPath, FileMode.Create))
          {
            file.CopyTo(stream);
          }
        }

        return Ok(fileName);
      }
      catch (System.Exception ex)
      {
        return BadRequest(ex.Message);
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

谢谢