uploadcare

How to implement minDimensions in Uploadcare Widget


Settings can be added to Uploadcare as follows:

var myDialog = uploadcare.openDialog(null, {
    imagesOnly: true,
    multiple: true,
    multipleMin: 1
    multipleMax: 7
});

Now how is minDimensions being set? The documentation shows minDimensions(800x600) but that notation doesn't work. The below attempt does not work:

var myDialog = uploadcare.openDialog(null, {
    imagesOnly: true,
    multiple: true,
    multipleMin: 1
    multipleMax: 7,
    minDimensions: '800,600'
});

Following doesn't work either:

var myDialog = uploadcare.openDialog(null, {
    imagesOnly: true,
    multiple: true,
    multipleMin: 1
    multipleMax: 7,
    minWidth: 800,
    minHeight: 600
});

Additionally, it's unclear what happens if an uploaded image dimenions is less than these settings. Does the Widget show an error?


Solution

  • minDimensions, as well as minWidth and minHeight, are not widget options. The link refers to file validation docs. File validation is a function that invokes before the file is completely uploaded, and have access to the fileInfo object so that you can check file parameters (size, name, image dimensions, etc.) and abort uploading if some parameter doesn't match your requirements.

    To set an image dimension validator, you'd need to define a validation function first

    function minDimensions(width, height) {
      return function(fileInfo) {
        var imageInfo = fileInfo.originalImageInfo;
        if (imageInfo !== null) {
          if (imageInfo.width < width || imageInfo.height < height) {
            throw new Error('dimensions');
          }
        }
      }
    }
    

    Then, when you open a dialog, you add the validation function to the validators array in the dialog settings

    var myDialog = uploadcare.openDialog(null, {
        imagesOnly: true,
        multiple: true,
        multipleMin: 1,
        multipleMax: 7,
        validators: [minDimensions(800, 600)]
    });
    

    If a file doesn't pass the validation, the widget will show the default error message - "Can't upload", but you can customize the error message using the UPLOADCARE_LOCALE_TRANSLATIONS option

    UPLOADCARE_LOCALE_TRANSLATIONS = {
      // messages for widget
      errors: {
        'dimensions': 'The image has to be 800x600px or larger.'
      },
      // messages for dialog’s error page
      dialog: { tabs: { preview: { error: {
        'dimensions': {
          title: 'Error.',
          text: 'The image is too small. Try to upload another one.',
          back: 'Back'
        }
      } } } }
    };