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

标签 c# angular asp.net-web-api httpclient 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;
    })
  }
 }

这是我的服务代码:

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

这是我的 Web API 代码:

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

            var file = Request.Form.Files[0];
            HttpRequest formData = HttpContext.Request;
        }
    }

如何使用 HttpClient 从 Angular 向 Web API 发送文件。我在 Web API 中遇到错误,例如“不正确的内容类型:application/json”

最佳答案

在 Angular 站点使用此代码

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);
      }
    });
  }

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

<input #file type='file' multiple (change)="onSelectFile($event, file.files)">

然后在您的 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);
      }
    }
  }

谢谢

关于c# - 使用 Angular 6 将文件上传到 Web Api C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53613859/

相关文章:

c# - .NET Core RedirectToAction 不重定向

angular - 无法使用 [formControlName] 禁用 matInput 元素

javascript - 等待加载 html,直到从异步进程加载引用的 js 值?

angular - 你能在 Angular 2(使用 Typescript)中返回一个 observable 作为 promise 吗?

c# - 如何在 Web Api 中使用 Api key 使用表单例份验证进行服务身份验证

asp.net-web-api - 405 使用 AttributeRouting.PUTAttribute 时,除非我还包含 HttpPutAttribute

c# - 为什么我在将可为 null 的整数设置为属性时遇到问题?

c# - 尝试捕捉并清理

c# - 递归搜索目录 n 个目录深度

c# - 是否有更有效的方法来转换已经包含对 XSLT 的引用的 XDocument?