首页 > 解决方案 > Angular 5 和 ASP.NET Core 2.0 Web API 文件上传 - 文件损坏

问题描述

我正在尝试从我的 Angular 5 客户端应用程序上传 ASP.NET Core 类库文件 (DLL)。在服务器端,我有一个 ASP.NET Core 2.0 Web API 来接收上传的文件。我使用了标准推荐机制。客户端代码如下

 uploadAssemblyFile(file: File): any {
      const formdata: FormData = new FormData();
      formdata.append('file', file, file.name);
      const endpoint = '/api/upload';
      const req = new HttpRequest('POST', endpoint, formdata, {
        reportProgress: true,
        responseType: 'json'
      });

      return this.http.request(req);
  }

服务器端代码如下,

    [HttpPost()]
    [Route("api/upload")]
    public async Task<IActionResult> UploadAssembly(IFormFile file)
    {
        long size = file.Length;
        var uploads = Path.Combine(Directory.GetCurrentDirectory(), "uploads");

        if (file != null && file.Length > 0)
        {
            using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
            {
                await file.CopyToAsync(fileStream);                        
            }
        }


        return Ok();
    }

Web API 被正确调用,IFormFile 具有所有必需的详细信息。文件被保存。但是,该文件似乎已损坏。使用 Windows 上的属性看到的原始文件和上传文件的大小不同。

PNG文件也是如此。但是,TXT 文件似乎可以正确上传。

有没有人遇到过类似的情况。我看了几个帖子,但没有得到必要的答案。

任何指针肯定会有所帮助。提前致谢

标签: c#asp.netangular

解决方案


推荐阅读