When utilizing "ng2-file-upload" in conjunction with Angular 2 and Typescript, encountering a limitation where files larger than 1MB cannot be uploaded

My attempt to upload a file with a size exceeding 1MB is triggering an error regarding its large size. Despite setting the limit to 50 MB, it doesn't seem to be working as expected. Can someone please assist me in figuring out what I am doing incorrectly?

 @Component({
        moduleId: module.id,
        //define the element to be selected from the html structure.
        selector: 'NeedAnalysisConsult',
        //location of our template rather than writing inline templates.
        templateUrl: 'need-analysis-consultation.component.html',

    })
    export class NeedAnalysisConsultationComponent implements OnInit {
        model:any={};
        consultationDate: Date;
        organisation: string;
        devCode:String;
        maxFileSize = 50 * 1024 * 1024;


         //declare a property called fileuploader and assign it to an instance of a new fileUploader.
        //pass in the Url to be uploaded to, and pass the itemAlais, which would be the name of the //file input when sending the post request.
        public uploader:FileUploader = new FileUploader({url: URL,isHTML5: true, itemAlias: 'consultation',maxFileSize: this.maxFileSize});
        //This is the default title property created by the angular cli. Its responsible for the app works
        title = 'app works!';

        ngOnInit() {
        //override the onAfterAddingfile property of the uploader so it doesn't authenticate with //credentials.
          this.uploader.onAfterAddingFile = (file)=> { file.withCredentials = false; };
          this.uploader.onBuildItemForm=(item:any,form:any)=>{
                form.append('devCode',this.model.programmeCode);
                form.append('date',this.model.consultationDate);
                form.append('organization',this.model.organisation);

          };
        //overide the onCompleteItem property of the uploader so we are
        //able to deal with the server response.
          this.uploader.onCompleteItem = (item:any, response:any, status:any, headers:any) => {
                console.log("FileUpload:successfully uploaded:", item, status, response);
                if (status==201){

                  alert("FileUpload: successfully");

                }
                else {
                 alert("FileUpload:"+response);

              }

            };
        }

Having trouble uploading a file larger than 1MB and encountering issues due to its size limitation set at 50MB. Any guidance on where I may be going wrong would be greatly appreciated.

Answer №1

After conducting thorough testing of your approach, I can confirm that it is successfully uploading on my server without any issues. It is important to verify that your server settings allow for the acceptance of files larger than 1 MB. To verify and troubleshoot any potential server-side errors, you may consider implementing callback functions similar to those used in the onCompleteItem method.

function onSuccessItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
    // This function will execute once when the first file is uploaded
}
function onErrorItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
    let error = JSON.parse(response); // Capture and handle server-side errors here
}

To utilize these callback functions effectively, subscribe to them as demonstrated below:

this.uploader.onErrorItem = (item, response, status, headers) => this.onErrorItem(item, response, status, headers);
this.uploader.onSuccessItem = (item, response, status, headers) => this.onSuccessItem(item, response, status, headers);

By following this approach, you will have a systematic way to diagnose whether any encountered errors originate from the server side during file uploads.

Answer №2

There are only two possible reasons for this issue:

On the Client Side: if the ng2-file-upload maxFileSize setting is lower than 1MB

On the Server Side: If you are using PHP, make sure to adjust the following settings in the php.ini file

  1. post_max_size = 50M # This means that a single post request should not exceed 50MB, regardless of how many files are being uploaded.

  2. upload_max_filesize = 50M # Indicates that no individual file can be larger than 50MB per request

  3. max_file_uploads = 10 # Specifies that only up to 10 files can be uploaded in a single request

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

Utilizing an Angular component for multiple purposes

For my Angular app, which is component-based and uses Angular version 1.5.5 with TypeScript, I have a header component that includes a country dropdown. This header component is used across multiple pages. However, when a country is selected from the dropd ...

failure to render updated content after modification of variable

I am facing an issue with triggering a function in the component: componentA.ts html = 'hey'; this.onElementSelected(r => this.change()); public change() { console.log(this.html); if (this.html === 'hey&ap ...

Utilize Property Binding to Access the Map

I am struggling to extract a value from a Map and use it as the background color of a div element, but I can't seem to get it right. My syntax seems off. What mistake am I making? <div [style.background-color]="bgcolor" width="50px" height="50px"& ...

Nested interfaces can utilize sum types

An example showcasing the use of sum types: interface Cash { amount: number, type: 'cash' } interface Card { amount: number, type: 'card', cardNumber: string } type Payment = Cash | Card const displayPayment = (payment: Pay ...

Having trouble with an unexpected value in your Angular2 Service? Don't forget to add

I encountered an error in my Angular2 app: Error: (SystemJS) Unexpected value 'ReleasesService' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation. Here is my AppModule code: import { NgModule } fr ...

"Error message: TypeORM DataSource encounters a password issue with the client

Here is the content of my data-source.ts file: import {DataSource} from "typeorm"; import path from "path"; import {User} from "./entity/User"; import { config } from "dotenv"; config(); export const AppDataSource ...

Taking a segmented snapshot of a canvas using a flexible design scheme

I am working with a canvas that contains multiple div elements representing different sections of the canvas. However, when I capture these sections, they do not appear exactly as displayed on the screen. How can I track and accurately capture the div area ...

Can someone provide guidance on utilizing parentheses in HTML code?

I am facing an issue in my Angular project while using the WordPress API. The problem lies in the API address structure which includes "" like this: <img src="{{importantvideo.better_featured_image.media_details.sizes.["covernews-med ...

Angular: Nested FormArray not populating the values in the FormControls

I have a form that contains a FormArray inside which you can dynamically add values and in this case I can retrieve the values using the FormControl. const formGroup = this._formBuilder.group({ dataArray: new UntypedFormArray([]), }); Inside this first ...

Issue with my TypeScript modules TS2307: Module not found

For my latest project, I decided to use the aurelia-typescript-skeleton as the foundation. To enhance it, I created a new file called hello.ts in the src folder. export class Hello { sayHello(name:string) : string { return 'Hello ' + name; ...

Batch requesting in Typescript with web3 is an efficient way to improve

When attempting to send a batch request of transactions to my contract from web3, I encountered an issue with typing in the .request method. My contract's methods are defined as NonPayableTransactionObject<void> using Typechain, and it seems tha ...

Errors are being encountered by npm during the execution of tsc and concurrently when running the start command

Every time I attempt to execute npm start, a series of errors pop up on my screen... 19 error node v4.2.0 20 error npm v3.10.5 21 error code ELIFECYCLE 22 error <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d1f081e180008400 ...

Angular does not include the ControlGroup feature in its common offerings

I am new to TypeScript and have been following tutorials in an attempt to accomplish simple tasks, but so far without success. Many tutorials seem outdated with changes in Angular or provide instructions that do not work at all. Even the tutorials that do ...

Error encountered in Node.js OpenAI wrapper: BadRequestError (400) - The uploaded image must be in PNG format and cannot exceed 4 MB

Attempting to utilize the OpenAI Dall-e 2 to modify one of my images using the official Nodejs SDK. However, encountering an issue: This is the snippet of code: const image = fs.createReadStream(`./dist/lab/${interaction.user.id}.png`) const mask = fs.c ...

The path referenced in typings is incorrect

I am currently facing an issue with my Typescript library that I am trying to publish on npmjs. It seems like the types file is not being exported correctly. The library has a simple method in the src/index.ts file and typings from src/typings/index.d.ts. ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...

The best approach to integrating Axios with TypeScript

I'm facing an issue in my application that I've been struggling to resolve. My setup involves using axios combined with TypeScript. Here's a snippet of the code where the problem lies: export const fetchTransactions = (PageNum: number, PageS ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Having trouble with Updating the Records in NodeJs and Angular

As a beginner in Node.js with Angular, I have been working on a simple CRUD application. Adding, deleting, and viewing records works fine for me. However, I am facing issues with updating records. Whenever I make changes on the form and click the submit bu ...

Using Angular to include more than two parameters in an HTTP GET request

Currently, I am developing an application that requires downloading a file upon clicking a button within a template. The screen displays multiple files, each with its own corresponding button. I need to send the index number of the array to Angular and pas ...