Is it possible to limit the size of uploaded images?

If I want to limit the size of images uploaded from an input of type: 'file', is it possible to do so?

I referred to:

It seems that you can only restrict the image format through allowedFileTypes.

Can I achieve this from within the onChange ?

Or do you have any other suggested solutions?

Hello @nnn,

In Builder.io, the input type file does allow you to restrict the formats of the uploaded files using the allowedFileTypes option. However, if you want to limit the size of the images uploaded, you’ll need to handle this validation logic yourself after the file has been selected.

Yes, you can achieve size validation using the onChange event in a couple of ways:

  1. Client-side Validation:

    • When a file is selected, you can capture the file details through the onChange handler.
    • Check the file size property (file.size) before allowing further processing.
  2. Example Code:

    function handleFileChange(event) {
      const file = event.target.files[0];
      const fileSizeLimit = 2 * 1024 * 1024; // 2 MB
    
      if (file && file.size > fileSizeLimit) {
        alert("The file size should be less than 2 MB");
        // Clear the input field or prevent further processing
        event.target.value = null;
      }
    }
    
  3. Server-side Validation:

    • You can also perform size validation on the server-side as a second line of defense when the file is uploaded to the server.

While the allowedFileTypes helps with constraining the file format, you do need to handle size constraints in your code either through JavaScript for immediate feedback or on the server-side when handling the uploaded file.

For more details about managing custom components and their inputs, see the Input Types for Custom Components documentation.

I hope this helps!

Thanks,