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

Importing images in Typescript is a simple and effective

I came across a helpful solution at this Stackoverflow thread However, I encountered an error: [ts] Types of property 'src' are incompatible. Type 'typeof import("*.png")' is not assignable to type 'string | undefined& ...

"Exploring the power of D3, TypeScript, and Angular 2

I am facing challenges incorporating D3 v4 with Angular 2 (Typescript). While exploring D3 v4, I have referred to several solutions on StackOverflow without success. I have imported most of the necessary D3 libraries and typings (utilizing TS 2.0) and adde ...

Using TypeScript, creating a tagged template literal for running Jest tests with the `test.each`

Struggling to construct a jest test.each with a tagged template literal test.each` height | text ${10} | ${undefined} ${20} | ${undefined} ${10} | ${'text'} ${20} | ${'text'} `('$height and $text behave as expected&a ...

NativeScript Error Code NG8001: Element 'ActionBar' is unrecognized

In my project, the startupscreen module setup is as follows: import { NativeScriptFormsModule } from "@nativescript/angular"; import { NativeScriptCommonModule } from "@nativescript/angular/common"; import { NgModule, NO_ERRORS_SCHEMA } ...

How can props be defined in Vue3 using Typescript?

When using Vue3's defineComponent function, it requires the first generic parameter to be Props. To provide props type using Typescript interface, you can do it like this: export default defineComponent<{ initial?: number }>({ setup(props) { ...

Adding connected types to a list using Typescript

Question regarding Typescript fundamentals. In my code, I have a list that combines two types using the & operator. Here is how it's initialized: let objects: (Object & number)[] = []; I'm unsure how to add values to this list. I attem ...

The variable 'FC' has been defined, however it is not being utilized. This issue has been flagged by eslint's no-unused

After running eslint, I encountered a warning stating that X is defined but never used for every type imported from react or react-native. For example, this warning appeared for FC and ViewProps (refer to the image below). Below is my .eslintrc.js configu ...

Leveraging AWS CDK to seamlessly integrate an established data pipeline into your infrastructure

I currently have a data pipeline set up manually, but now I want to transition to using CDK code for management. How can I achieve this using the AWS CDK TypeScript library to locate and manage this data pipeline? For example, with AWS SNS, we can utilize ...

Is it a good idea to separate TypeScript types into their own package?

In my React/TypeScript application, I have approximately 100 files where various types are declared. I am looking for a simpler and more automated approach to extract all these types into a separate package. Is there a method other than manually copying ...

Attempting to display two separate d3 line graphs within a single Ionic2 page

I am facing an issue with including multiple similar graphs on a single page within an Ionic2 application. I am utilizing the d3-ng2-service to wrap the d3 types for Angular2. The problem arises when attempting to place two graphs in separate div elements ...

Transforming a plain text field into an input field upon clicking a button or icon using Angular/Typescript

I am a beginner with Angular 6 and I'm trying to implement functionality where clicking a button or icon will change a text field into an input field. See the snippet of code and expected output below. Thank you in advance. <div> <mat-for ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

TypeScript Interfaces: A Guide to Defining and

In my angular2 application, I have created interfaces for various components. One of these interfaces is specifically for products that are fetched from a remote API. Here is the interface: export interface Product { id: number; name: string; } ...

Error encountered in Next.js: The function 'useLayoutEffect' was not successfully imported from 'react' (imported as 'React')

I've been in the process of migrating an application from CSR (using webpack only) to SSR, and I'm utilizing Next.js for this transition. Following the migration guide provided by Next.js for switching from vite (specifically focusing on parts r ...

What are some ways to implement Material UI's Chip array to function similar to an Angular Chip Input?

Can the sleek design of Angular Material's Chip input be replicated using a React Material UI Chip array? I am attempting to achieve the modern aesthetic of Angular Material Chip input within React. While the Material UI Chip array appears to be the ...

Pattern Matching for Excluding Multiple Specific Phrases

I need to restrict what a user can enter into a field based on previous entries that are already in the system. For instance, the user has already entered these values into the database: ["typescript", "C#", "python"] If they type one of these existing ...

What is the process for setting up custom global interfaces in TypeScript using .d.ts files?

I'm currently facing an issue in my ReactJS project using Webpack2 and TypeScript. Everything is functioning perfectly except for one thing - I've been struggling to move my self-written interfaces into separate files so they are accessible throu ...

Tips for extracting the y-coordinate from a touch event using d3

I am utilizing d3.js to display data in my Ionic app. I have a touch event that allows me to move a line and retrieve the coordinates where it intersects with my chart. While I can easily obtain the x-coordinate representing the date, I am struggling to ge ...

There is a lint error that is thrown when upgrading the typings file for JQuery version 3.2

I recently encountered an issue in my application where I used the following interface. It worked perfectly with jQuery 2.0: interface JQuery{ data(key: any): any; } However, upon upgrading to jQuery 3.2, the following lint errors were thrown: All decla ...

Is there a type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired. I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others. Now, I have implemented a ...