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!
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 :
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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With