Limit file upload size to less than 1MB in Angular 2 with typescript using ng2-file-upload

Having issue with my code - I can't upload a file larger than 1mb even though maxFileSize is set to 50mb. Can anyone help me troubleshoot?

@Component({
    moduleId: module.id,
    selector: 'NeedAnalysisConsult',
    templateUrl: 'need-analysis-consultation.component.html',

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

    public uploader:FileUploader = new FileUploader({url: URL,isHTML5: true, itemAlias: 'consultation',maxFileSize: this.maxFileSize});
    
    title = 'app works!';

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

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

        };
    }
    
    constructor(private http: Http, private el: ElementRef,private router:Router,private _location: Location) {

    }
    @ViewChild('selectedFile') selectedFile: any;
    clear(){
      this.model.programmeCode="";
      this.model.organisation="";
      this.model.consultationDate=null;
      this.selectedFile.nativeElement.value = '';
       (<HTMLInputElement>document.getElementById("file-name")).value = "";
    }
     updateFile(){
       (<HTMLInputElement>document.getElementById("file-name")).value = "";
       for(var i = 0;i<this.uploader.queue.length;i++){
        if(i != 0)
          (<HTMLInputElement>document.getElementById("file-name")).value += " ; "+this.uploader.queue[i].file.name;
         else
          (<HTMLInputElement>document.getElementById("file-name")).value = this.uploader.queue[i].file.name;
        console.log(this.uploader.queue[i].file.name);
      }
     }

     close() {
        console.log("closing the window...");
        this.router.navigate(['/home']);
    }
    removefile(){
        (<HTMLInputElement>document.getElementById("file-name")).value = "";
    }
      backClicked() {
        this._location.back();
    }

}

Struggling to figure out why files over 1mb cannot be uploaded despite setting maxFileSize to 50mb in my code. Any advice would be appreciated.

Answer №1

Give this a shot within your .component.ts file :

ngOnInit() {
let maxAllowedSize = 8 * 1024 * 1024; // adjust this to set your preferred maximum file size
this.fileHandler = new FileUploader({ 
  url:this.uploadUrl, removeAfterUpload: false, 
  autoUpload: false,
  method:'post',
  maxFileSize:maxAllowedSize
});

  this.fileHandler.onWhenAddingFileFailed = (item, filter) => {
    let message = '';
    switch (filter.name) {
      case 'fileSize':
        message = 'Attention ! \nThe uploaded file \"' + item.name + '\" is ' + this.formatBytes(item.size) + ', which exceeds the maximum allowable size of ' + this.formatBytes(maxAllowedSize);
        break;
      default:
        message = 'Error encountered while trying to upload file '+item.name;
        break;
    }

    alert(message);
  };
}

formatBytes(bytes, decimals?) {
  if (bytes == 0) return '0 Bytes';
  const k = 1024,
    dm = decimals || 2,
    sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

Answer №2

When working with the normal tomcat server application, a limitation is in place that prevents files larger than 1 MB from being uploaded, leading to errors.

To troubleshoot this issue, check the api console (java/.net) for detailed error messages.

To address this problem, consider setting the maximum file size allowed by the api. For guidance on how to do this, refer to this link.

If you encounter multipart errors, consult this link for further information.

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

Warning: The attribute 'EyeDropper' is not recognized within the context of 'Window & typeof globalThis'

Attempting to utilize "window.EyeDropper" in a project that combines vue2 and TypeScript. When writing the following code: console.log(window.EyeDropper); An error message is generated by my Vetur plugin: Property 'EyeDropper' does not exist on ...

Angular: finding out if Observable or BehaviorSubject has undergone any important modifications

I am facing an issue with my user object in a membership service. I need to ensure that my services are updated only when there are relevant changes in the user object. To determine if there are relevant changes in the user object, I compare it with the ...

Ways to immediately display an uploaded image as the background on a canvas

Using TypeScript, I am attempting to set an uploaded image as the background of a canvas. However, I am facing an issue where the image only loads properly after the user has uploaded it two times. How can I ensure that the image has finished loading befor ...

Exploring methods to retrieve the status attribute of an Angular httpClient response

Here is the code snippet that I am working with: this.http.post(url, payload) .subscribe( (req:any)=>{ if(req.status != 200){ console.log('non 200 status'); The this.http in my code refers to a service tha ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

Issues with sending emails through Nodemailer in a Next.js project using Typescript

I'm currently working on a personal project using Nodemailer along with Next.js and Typescript. This is my first time incorporating Nodemailer into my project, and I've encountered some issues while trying to make it work. I've been followin ...

Encountered an issue with locating the module 'webpack-cli/bin/config-yargs' while attempting to run webpack-dev

Encountering an error while trying to start the webpack dev server with the command provided below. Despite suggestions that it could be due to outdated webpack versions, I am confident that all components are up to date: [email protected] [email ...

I require assistance in comprehending async/await in order to ensure that the code will pause and wait for my http.get function to

I've been reading various articles and forums, both here and on Google, about using awaits and asyncs in my code. However, no matter where I place them, the code after my http.get call always executes first. The alert messages from the calling program ...

Error message: NextJs throws aReferenceError when trying to access the document object on page refresh

encountered the error ReferenceError: document is not defined when attempting to refresh the page I am working on creating a component using react-quill and then calling that component within a page. This is my component : import React, { useState } from ...

Personalized context hook TypeScript

I have been experimenting with a custom hook and the context API, based on an interesting approach that I found in this repository. However, I encountered an error when trying to use it with a simple state for a number. Even though I wanted to create a mo ...

Guide to making a Typescript type guard for a ReactElement type

I'm currently working with three TypeScript type guards: const verifyTeaserOne = (teaser: Teaser): teaser is TeaserOneType => typeof teaser === 'object' && teaser.type.includes('One'); const validateTeaserTwo = ( ...

The nz-switch function is malfunctioning as a result of an update that has affected its value

<form [formGroup]="businessFoodHygieneForm"> <div class="box p-4 d-flex jc-between ai-center"> <span> Food Hygiene Link </span> <label> <nz-switch class="switch- ...

Choose a row by selecting the checkbox in the Kendo UI grid using TypeScript

I'm just starting out with Kendo UI and Angular 2, and I'm currently working on integrating Kendo UI with Angular 2. Specifically, I have a Grid Module set up with checkboxes in each row. My goal is to extract the row ID or any other field value ...

Bringing in the RangeValue type from Ant Design package

Currently working on updating the DatePicker component in Ant Design to use date-fns instead of Moment.js based on the provided documentation, which appears to be functioning correctly. The suggested steps include: import dateFnsGenerateConfig from ' ...

Steps for integrating the ts component into the index.html file

Is there a way to add the ts component in the index.html file? I've been looking for a solution for quite some time now, but haven't had any luck. Can anyone offer any suggestions or help? ...

What is the best way to bring two useStyles files into a single TypeScript file?

I am having an issue with finding a declaration file for the module 'react-combine-styles' even after I installed it using npm install @types/react-combine-styles. import React, { useState } from "react"; import useStyles from "./u ...

Restricting a checkbox to a maximum of 5 checkmarks

In a multi-column table, each column is represented by a checkmark. I want to limit the ability to tick a checkmark to only 5 checkmarks. Here is the code that has been implemented: <tbody> <ng-container *ngFor="let col of testData" ...

Is there a function in Zod similar to Yup's oneOf()?

If I wanted to restrict a property to specific values using Yup, it could be achieved with the code snippet below: prop: Yup.string().oneOf([5, 10, 15]) However, I haven't found a similar method in Zod. Nonetheless, I can still validate it by: const ...

The TypeScript error message states, "The property 'breadcrumb' is not found within the type 'Data'."

My Breadcrumb Component is functioning properly when compiled to JavaScript and displaying the desired output. However, my IDE is showing an error message that I am struggling to fix. The error states: [ts] Property 'breadcrumb' does not exist o ...

Having trouble accessing props on children in TypeScript while using React.Children.toArray?

When using React.Children.toArray in Typescript, the props object on children is not detected. In order to address this issue, I am currently using any[] instead of ReactChild[], as props are not recognized on a array item when using the latter. Can someon ...