【问题标题】:Unable to File Upload From Angular 8 to Asp.net Core 2.2无法将文件从 Angular 8 上传到 Asp.net Core 2.2
【发布时间】:2019-11-03 23:00:56
【问题描述】:

我有 FileUploadController 的 asp.net 核心服务器(使用 .net 核心 2.2),它监听传入文件的发布请求。

[HttpPost("Upload")]
// public async Task<IActionResult> Upload([FromForm(Name="file")]IFormFile file) {
// public async Task<IActionResult> Upload([FromForm]IFormFile file) {
public async Task<IActionResult> Upload(IFormFile file) {
   Console.WriteLine("***" + file);
   if(file == null) return BadRequest("NULL FILE");
   if(file.Length == 0) return BadRequest("Empty File");
       Console.WriteLine("***" + host.WebRootPath);
   if (string.IsNullOrWhiteSpace(host.WebRootPath))
   {
      host.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
   }
   var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads");
   if (!Directory.Exists(uploadsFolderPath)) Directory.CreateDirectory(uploadsFolderPath);
       var fileName = "Master" + Path.GetExtension(file.FileName);
       var filePath = Path.Combine(uploadsFolderPath, fileName);
       using (var stream = new FileStream(filePath, FileMode.Create))
       {
          await file.CopyToAsync(stream);
       }
       return Ok("Okay");
}  

我创建了 Angular 应用程序(使用 Angular 版本 8),它可以选择要在 ClientApplication 上传的文件,并且我创建了三个调用 API“http://localhost:5000/api/fileupload/upload”的 post 服务。

  1. 标准 Angular HttpClient 帖子。服务器读取时,IFormFile 为空。

    const formData: FormData = new FormData();
    formData.append('file', file, file.name);
    // return this.http.post(this.endpoint, file);
    return this.http.post(this.endpoint, formData); // Problem solved
    

  1. 添加了 HttpHeaders,我尝试了空头、未定义和其他来自 stackoverflow 和 google 的建议解决方案。

    const header = new HttpHeaders() //1
    header.append('enctype', 'multipart/form-data'); //2
    header.append('Content-Type', 'multipart/form-data'); //3
    

如果我在请求中放入带有资源的 httpheader,服务器会给出 415(不支持的媒体类型)

  1. 我尝试来自 '@angular/common/http' 的 HttpRequest,它最终给了我想要的结果。

    const formData: FormData = new FormData();
    formData.append('file', file, file.name);
    const req = new HttpRequest('POST', this.endpoint, formData);
    return this.http.request(req);
    

我想知道这是一个错误还是我的误解?如果您查看在线教程,大多数开发人员使用“this.HttpClient.post”。 根据我的阅读,我可以使用 httpclient.post 并且 Angular 框架会自动为用户设置正确的标题。它似乎没有做这项工作。

经过排查,第一个错误是我使用文件的错误 而不是formData,第二个错误是标题“内容类型”声明 httpinterceptor 删除后,它会按预期加载文件。

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        // if (request.url.indexOf('/upload')) {
        //     return next.handle(request);
        // }
        const token = localStorage.getItem('token');
        const currentUser = JSON.parse(localStorage.getItem('user'));
        if (currentUser && token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${token}`,
                //    'Content-Type': 'application/json' <---- Main Problem.
                }
            });
        }
        return next.handle(request).pipe(catchError(err => this.handleError(err)));
    }
}

服务器:“https://github.com/phonemyatt/TestPlaygroundServer

客户:“https://github.com/phonemyatt/TestPlayground

【问题讨论】:

  • 试试这个:public async Task&lt;IActionResult&gt; Upload([FromForm] IFormFile file) {}
  • @PrashantPimpale 我已经尝试过使用 FromForm 属性,我仍然无法上传它

标签: c# angular typescript asp.net-core angular8


【解决方案1】:

下面的代码适合你

  uploadSecond(file: File) {
    const formData: FormData = new FormData();
    formData.append('file', file, file.name);
    return this.http.post('https://localhost:44393/api/fileupload/UploadSecond', formData);
  }

然后在你的控制器中

[HttpPost("UploadSecond")]
[DisableRequestSizeLimit]
public async Task<IActionResult> UploadSecond([FromForm]IFormFile file)

【讨论】:

  • 改成这个后出现这个错误。 System.IO.InvalidDataException:缺少内容类型边界
  • 尝试删除像return this.http.post(url, formData);这样的httpOptions,看看它是否有效
  • 它可以访问我的上传api,但文件始终为空。
  • 收到的文件始终为空。是角虫吗?
  • 您是否已经尝试过使用 [FromForm]IFormFile 文件和 IFormFile 文件?
【解决方案2】:

在第一个不起作用的示例中,您将file 传递给post(...) 而不是formData。应该是:

const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post(this.endpoint, formData);

您为控制器显示的代码似乎是正确的,因此这应该是唯一需要的更改。您确实不需要在从 Angular 发送的请求上设置任何自定义标头。

【讨论】:

    【解决方案3】:

    如果你在客户端使用 FormData,你可以得到这样的文件。

    [HttpPost("Upload"), DisableRequestSizeLimit]
            public ActionResult Upload()
            {
                try
                {
                    var file = Request.Form.Files[0];
                    var folderName = Path.Combine("Resources","Images");
                    var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
    
                    if (file.Length > 0)
                    {
                        var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        var fullPath = Path.Combine(pathToSave, fileName);
                        var dbPath = Path.Combine(folderName, fileName);
    
                        using (var stream = new FileStream(fullPath, FileMode.Create))
                        {
                            file.CopyTo(stream);
                        }
    
                        return Ok(new { dbPath });
                    }
                    else
                    {
                        return BadRequest();
                    }
                }
                catch (Exception ex)
                {
                    return StatusCode(500, "Internal server error");
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2020-10-05
      • 1970-01-01
      • 2021-03-23
      • 2020-06-12
      • 2020-04-08
      • 2016-06-09
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      相关资源
      最近更新 更多