Ошибка загрузки видео с использованием ng2-file-upload в Angular7 ASP .Net Core 2.1 - PullRequest
0 голосов
/ 31 января 2019

В своем проекте я использовал ng2-file-upload для загрузки фотографий и видео на сервер. Часть загрузки фото работает правильно.Но размер видеофайла, превышающего 27 МБ, не может быть загружен. Когда я вызываю метод Uploader.UploadAll, затем загружают метод hide, и загрузка файла автоматически отменяется. В консоли браузера отображается сообщение об ошибке

Failed to load resource: net::ERR_CONNECTION_RESET  

Я хочузагрузить видеофайл размером не менее 100 МБ.

Вот HTML-код

<div *ngIf="authService.currentUser && authService.currentUser.id == user.id" class="row mt-3">

  <div class="col-md-3">

      <h3>Upload files</h3>

      <div ng2FileDrop
           [ngClass]="{'nv-file-over': hasBaseDropZoneOver}"
           (fileOver)="fileOverBase($event)"
           [uploader]="uploader"
           class="card bg-faded p-3 text-center mb-3 my-drop-zone">
           <i class="fa fa-upload fa-3x"></i>
          Drop Videos Here
      </div>

   Single
      <input type="file" ng2FileSelect [uploader]="uploader" />
  </div>

  <div class="col-md-9" style="margin-bottom: 40px" *ngIf="uploader?.queue?.length">

      <h3>Upload queue</h3>
      <p>Queue length: {{ uploader?.queue?.length }}</p>

      <table class="table">
          <thead>
          <tr>
              <th width="50%">Name</th>
              <th>Size</th>

          </tr>
          </thead>
          <tbody>
          <tr  *ngFor="let item of uploader.queue">
              <td><strong>{{ item?.file?.name }}</strong></td>
              <td *ngIf="uploader.options.isHTML5" nowrap>{{ item?.file?.size/1024/1024 | number:'.2' }} MB</td>

          </tr>
          </tbody>
      </table>

      <div>
          <div>
              Queue progress:
              <div class="progress mb-4">
                  <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': uploader.progress + '%' }"></div>
              </div>
          </div>
          <button type="button" class="btn btn-success btn-s"
                  (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
              <span class="fa fa-upload"></span> Upload
          </button>
          <button type="button" class="btn btn-warning btn-s"
                  (click)="uploader.cancelAll()" [disabled]="!uploader.isUploading">
              <span class="fa fa-ban"></span> Cancel
          </button>
          <button type="button" class="btn btn-danger btn-s"
                  (click)="uploader.clearQueue()" [disabled]="!uploader.queue.length">
              <span class="fa fa-trash"></span> Remove
          </button>
      </div>

  </div>

</div>

Вот мой машинописный код

initializeUploader() {
    this.uploader = new FileUploader({
      url: this.baseUrl + 'api/users/' + this.authService.decodedToken.nameid + '/videos',
      authToken: 'Bearer ' + localStorage.getItem('token'),
      isHTML5: true,
      allowedFileType: ['video'],
      removeAfterUpload: true,
      autoUpload: false,
      maxFileSize: 100 * 1024 * 1024

    });

    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };

    this.uploader.onSuccessItem = (item, response, status, headers) => {
      if (response) {
        const res: Video = JSON.parse(response);
        const video = {
          id: res.id,
          url: res.id,
          dateAdded: res.dateAdded,
          description: res.description,
          fileExtension: res.fileExtension,
          thumbs: ''
        };
        this.videos.push(video);
      }
    };
  }

Скажите, пожалуйста, как решить эту проблему,Эта проблема возникает, если я выбираю размер файла больше 27 МБ.

спасибо

1 Ответ

0 голосов
/ 02 февраля 2019

Я решил эту проблему, изменив файл program.cs. Это не проблема с библиотекой ng2-file-upload. В моем случае мой проект выполняется на сервере kestrel, поэтому я добавил эту строку в файл program.cs.

 .UseKestrel(options =>
          {
             options.Limits.MaxRequestBodySize = 209715200;
          })

здесь находится код извлечения

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging(builder =>
                     {
                         builder.SetMinimumLevel(LogLevel.Warning);
                         builder.AddFilter("ApiServer", LogLevel.Debug);
                         builder.AddSerilog();
                     })
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseKestrel(options =>
              {
                 options.Limits.MaxRequestBodySize = 209715200;
              })
            .UseStartup<Startup>();

Затем после того, как я добавил атрибуты [RequestFormLimits] и [RequestSizeLimit] поверх метода upload () в моем классе контроллера

[RequestFormLimits(MultipartBodyLengthLimit = 209715200)]
[RequestSizeLimit(209715200)]
public async Task<IActionResult> Upload(Guid userId,
        [FromForm]VideoForCreationDto videoForCreationDto)
    {}

Если вы используете сервер iis, добавьте этот код в файл web.config. На самом деле я получил этот код из другого места. Так что я не уверен в этом. Я подумал, что это полезно для некоторыхВот почему добавление этого кода.

<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="209715200" />
    </requestFiltering>
  </security>
</system.webServer>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...