i.am.michiel
i.am.michiel

Reputation: 10404

Howto validate image upload in PlayFramework 1?

I have to upload pictures with a few conditions :

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

Thanks!

Upvotes: 11

Views: 2369

Answers (2)

i.am.michiel
i.am.michiel

Reputation: 10404

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

Upvotes: 13

Felipe Oliveira
Felipe Oliveira

Reputation: 1041

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

Upvotes: 1

Related Questions