在Angular7 ASP .Net Core 2.1中使用ng2-file-upload,视频上传失败

时间:2019-01-31 19:30:30

标签: typescript angular7 asp.net-core-2.1

在我的项目中,我使用ng2-file-upload将照片和视频上传到服务器。照片上传部分工作正常。但是大于27MB的视频文件无法上传。当我调用Uploader.UploadAll方法时,上传方法hide和文件上传会自动取消。在浏览器控制台中显示一个名为

的错误
Failed to load resource: net::ERR_CONNECTION_RESET  

我要上传至少100MB的视频文件。

这是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);
      }
    };
  }

请告诉我如何解决此问题,如果我选择文件大小大于27MB,则会发生此问题。

谢谢

1 个答案:

答案 0 :(得分:0)

我通过更改program.cs文件解决了这个问题。这不是ng2-file-upload库的问题。在我的情况下,我的项目在kestrel服务器上运行,因此我将此行添加到program.cs文件中。 / p>

 .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>();

然后,在我的控制器类的upload()方法之上添加[RequestFormLimits]和[RequestSizeLimit]属性

[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>