Issue with uploading video files using ng2-file-upload in Angular7 and ASP .Net Core 2.1

While working on my project, I encountered an issue with uploading video files using ng2-file-upload to the server. The photo upload functionality is working fine, but when attempting to upload a video file larger than 27MB, the process gets canceled automatically once Uploader.UploadAll method is called. An error message "Failed to load resource: net::ERR_CONNECTION_RESET" appears in the browser console.

I need to be able to upload video files of at least 100MB in size.

Below is the HTML code snippet:

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

The TypeScript code for handling file uploads:

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

If you have any insights or solutions to resolve this problem, especially with regards to uploading files larger than 27MB, I would greatly appreciate it. Thank you.

Best regards,

Answer №1

To solve the issue, I made adjustments to the program.cs file. It's important to note that the problem did not stem from the ng2-file-upload library. In my specific case, my project was running on a kestrel server, so I incorporated the following line in the program.cs file:

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

Here is where the code should be placed:

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

Following this update, I added [RequestFormLimits] and [RequestSizeLimit] attributes above the upload() method in my controller class.

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

If you are using an IIS server, consider adding the following code snippet to the web.config file. While I came across this code elsewhere and cannot completely vouch for it, I believe it could benefit someone facing a similar challenge.

<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="209715200" />
    </requestFiltering>
  </security>
</system.webServer>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting image upload issues with AWS S3 in Next.js version 13

I encountered a consistent problem with using the AWS SDK in NextJS to upload images. I keep getting error code 403 (Forbidden). Could there be other reasons why this error is occurring besides the accessKeyId and secretAccessKey being invalid? Below is my ...

Troubleshooting Issue: Angular 6 - Authentication token interceptor not including headers

After experimenting with various approaches using Angular 6 for the past couple of days, I recently tried implementing a solution mentioned in this post: . Despite my efforts, the header in the requests still remains unset. import {Inject, Injectable} fro ...

Cannot display value in NumericFormat when using MUI TextField due to prefix restrictions

When using MUI TextField with the NumericFormat and prefix prop, there seems to be an issue. If I start typing a number quickly, only one digit gets registered. On the other hand, if I type slowly all my numbers show up but the prefix disappears. All inp ...

What are the steps to create a dynamic navigation menu in Angular 2?

I have successfully implemented this design using vanilla CSS and JS, but I am encountering challenges when trying to replicate it in Angular 2. Setting aside routing concerns, here is the current state of my component: navbar.component.ts import { Comp ...

Transform a standard array of strings into a union string literal in TypeScript

I'm currently developing a module where users can specify a list of "allowable types" to be utilized in other functions. However, I'm encountering challenges implementing this feature effectively with TypeScript: function initializeModule<T ex ...

React | What could be preventing the defaultValue of the input from updating?

I am working with a stateful component that makes a CEP promise to fetch data from post offices. This data is retrieved when the Zip input contains 9 characters - 8 numbers and a '-' - and returns an object with the desired information. Below is ...

The variable 'user' is being accessed before being properly initialized - in Angular

I've been doing some research on Google and StackOverflow to try and troubleshoot this error, but I'm still having trouble getting it fixed. Can anyone provide assistance? Below is the content of my auth-service.ts file: import { Injectable } fr ...

What exactly does the context parameter represent in the createEmbeddedView() method in Angular?

I am curious about the role of the context parameter in the createEmbeddedView() method within Angular. The official Angular documentation does not provide clear information on this aspect. For instance, I came across a piece of code where the developer i ...

Ways to resolve issues related to null type checking in TypeScript

I am encountering an issue with a property that can be null in my code. Even though I check for the value not being null and being an array before adding a new value to it, the type checker still considers the value as potentially null. Can anyone shed lig ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

Typescript void negation: requiring functions to not return void

How can I ensure a function always returns a value in TypeScript? Due to the fact that void is a subtype of any, I haven't been able to find any generics that successfully exclude void from any. My current workaround looks like this: type NotVoid ...

Error encountered while attempting to globally install TypeScript using npm: "npm ERR! code -13"

Issue with npm error 13 Having trouble installing typescript-g package Error details: - errno: -13, - npm ERR! code: 'EACCES', - npm ERR! syscall: 'symlink', - npm ERR! path: '../lib/node_modules/typescript/bin/tsc', ...

Problem with selecting dates in rangepicker

Having trouble with my recursion code for selecting dates in a rangepicker: recurse( () => cy.get('.mantine-DatePicker-yearsListCell').invoke('text'), (n) => { if (!n.includes(year)) { //if year not f ...

Why am I unable to retrieve the property from the JSON file?

Below is the provided JSON data: data = { "company_name": "חברה לדוגמה", "audit_period_begin": "01/01/2021", "audit_period_end": "31/12/2021", "reports": [ ...

Unable to employ the inequality operator while querying a collection in AngularFire

I'm facing a challenge with pulling a collection from Firebase that is not linked to the user. While I've managed to query the user's collection successfully, I am struggling to retrieve the collection that does not belong to the user using ...

Issue encountered with TypeORM and MySQL: Unable to delete or update a parent row due to a foreign key constraint failure

I have established an entity relationship between comments and posts with a _many-to-one_ connection. The technologies I am utilizing are typeorm and typegraphql Below is my post entity: @ObjectType() @Entity() export class Post extends BaseEntity { con ...

Encountering issues with importing a module from a .ts file

Although I have experience building reactJS projects in the past, this time I decided to use Node for a specific task that required running a command from the command line. However, I am currently facing difficulties with importing functions from other fil ...

When Using TypeScript with Serverless, 'this' Becomes Undefined When Private Methods are Called from Public Methods

Currently, I am working on constructing an AWS Serverless function using TypeScript. My focus is on creating an abstract class with a single public method that invokes some private methods. Below is the simplified version of my TypeScript class: export ...

eliminate any redundant use of generics

Recently, I attempted to create a pull request on GitHub by adding generics to a method call. This method passes the generically typed data to an interface that determines the return type of its methods. However, the linter started flagging an issue: ERR ...