Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto validate image upload in PlayFramework 1?

I have to upload pictures with a few conditions :

  • dimensions cannot exceed x pixels height, y pixels width,
  • size cannot exceed b bytes on disk
  • has to be a PNG or a JPG file
  • has to be "resized"
  • has to be saved to disk (using play's Blob)

Si far, I've found little to no information on image upload and/or check for Play!Framework. Any help is welcome!

Thanks!

like image 920
i.am.michiel Avatar asked Jul 10 '11 23:07

i.am.michiel


2 Answers

After searching a little in PlayFramework's source code, I've stumbled upon ImageIO ibrary already used in Play. Cannot understand, why such easy checks have not been added to the core library...

Here's the check part, I've created for :

  • dimension check,
  • type check,
  • size check.

    package validators;
    
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    
    import play.Logger;
    import play.data.validation.Check;
    import play.db.jpa.Blob;
    import play.i18n.Messages;
    
    public class ImageValidator extends Check {
    
      public final static int MAX_SIZE = 4048;
      public final static int MAX_HEIGHT = 1920;
    
      @Override
      public boolean isSatisfied(Object parent, Object image) {
    
        if (!(image instanceof Blob)) {
            return false;
        }
    
        if (!((Blob) image).type().equals("image/jpeg") && !((Blob) image).type().equals("image/png")) {
            return false;
        }
    
        // size check
        if (((Blob) image).getFile().getLength() > MAX_SIZE) {
            return false;
        }
    
    
        try {
            BufferedImage source = ImageIO.read(((Blob) image).getFile());
            int width = source.getWidth();
            int height = source.getHeight();
    
            if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                return false;
            }
        } catch (IOException exption) {
            return false;
        }
    
    
        return true;
        }
    }
    
like image 163
i.am.michiel Avatar answered Nov 17 '22 08:11

i.am.michiel


Implement a custom check, here's a sample from Play's documentation:

public class User {

    @Required
    @CheckWith(MyPasswordCheck.class)
    public String password;

    static class MyPasswordCheck extends Check {

        public boolean isSatisfied(Object user, Object password) {
            return notMatchPreviousPasswords(password);
        }

    }
}

And here's a link to great post from Lunatech on file uploading with Play: http://www.lunatech-research.com/playframework-file-upload-blob

like image 42
Felipe Oliveira Avatar answered Nov 17 '22 07:11

Felipe Oliveira