首页 > 解决方案 > 使用 Angular 8 和 .Net Core Web API 上传大文件

问题描述

我正在尝试使用 .Net core Web Api 作为后端和 Angular 8 作为前端将大文件上传到服务器目录。

上传组件.ts

import { Component } from '@angular/core';
import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http'


@Component({
  selector: 'app-uploader',
  templateUrl: './uploader.component.html',
})
export class UploadComponent {
  public progress: number;
  public message: string;
  constructor(private http: HttpClient) { }

  upload(files) {
    if (files.length === 0)
      return;

    const formData = new FormData();

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

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

    this.http.request(uploadReq).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress)
        this.progress = Math.round(100 * event.loaded / event.total);
      else if (event.type === HttpEventType.Response)
        this.message = event.body.toString();
    });
  }
}

上传组件 HTML

<input #file type="file" multiple (change)="upload(file.files)" />
<br />
<span style="font-weight:bold;color:green;" *ngIf="progress > 0 && progress < 100">
  {{progress}}%
</span>

<span style="font-weight:bold;color:green;" *ngIf="message">
  {{message}}
</span>

<p><progress showValue="true" type="success" value={{progress}} max="100"></progress></p>

上传控制器

使用系统;使用 System.Collections.Generic;使用 System.IO;使用 System.Linq;使用 System.Net.Http.Headers;使用 System.Threading.Tasks;使用 Microsoft.AspNetCore.Hosting;使用 Microsoft.AspNetCore.Mvc;

// 有关为空项目启用 MVC 的更多信息,请访问https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebApplication2.Controllers
{
        [Produces("application/json")]
        [Route("api/[controller]")]
        public class UploadController : Controller
        {
            private IHostingEnvironment _hostingEnvironment;

            public UploadController(IHostingEnvironment hostingEnvironment)
            {
                _hostingEnvironment = hostingEnvironment;

            }

            [HttpPost, DisableRequestSizeLimit]
            public ActionResult 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);
                    }
                    if (file.Length > 0)
                    {
                        string 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 Json("Upload Successful.");
                }
                catch (System.Exception ex)
                {
                    return Json("Upload Failed: " + ex.Message);
                }
            }
        }

}

这适用于小文件。但是当涉及到大文件时,控件永远不会传递给 Web 控制器。控制台中出现此错误 在此处输入图像描述

标签: c#asp.net.netangularangular8

解决方案


我认为问题在于requestLimits->maxAllowedContentLength.net 核心配置中的属性。这是在 iis 和 kestrel 中解决它的链接


推荐阅读