Загрузка больших файлов с использованием Angular 8 и. Net Core Web API - PullRequest
1 голос
/ 12 февраля 2020

Я пытаюсь загрузить большие файлы в каталог сервера, используя Net core Web Api в качестве внутреннего интерфейса и Angular 8 в качестве внешнего интерфейса.

UploadComponent.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>

UploadController

с использованием System; using System.Collections.Generic; используя System.IO; использование System.Linq; using System. Net .Http.Headers; использование System.Threading.Tasks; использование Microsoft.AspNetCore.Hosting; using 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);
                }
            }
        }

}

Это прекрасно работает для маленькие файлы. Но когда дело доходит до больших файлов, управление никогда не переходит к веб-контроллеру. В консоли есть эта ошибка enter image description here

1 Ответ

1 голос
/ 12 февраля 2020

Я думаю, что проблема заключается в requestLimits->maxAllowedContentLength свойстве в. net конфигурации ядра. вот ссылка для ее разрешения в iis и kestrel

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...