【问题标题】:Howto validate image upload in PlayFramework 1?如何在 Play Framework 1 中验证图片上传?
【发布时间】:2011-10-02 10:17:03
【问题描述】:

我要上传图片有几个条件:

  • 尺寸不能超过 x 像素高度,y 像素宽度,
  • 大小不能超过磁盘上的 b 个字节
  • 必须是 PNGJPG 文件
  • 必须“调整大小”
  • 必须保存到磁盘(使用 play 的 Blob)

到目前为止,我几乎没有发现关于图片上传和/或检查 Play!Framework 的信息。 欢迎任何帮助!

谢谢!

【问题讨论】:

    标签: java image validation upload playframework


    【解决方案1】:

    在 PlayFramework 的源代码中搜索了一下后,我偶然发现了 ImageIO ibrary 已在 Play 中使用。无法理解,为什么没有将这么简单的检查添加到核心库中......

    这是我创建的检查部分:

    • 尺寸检查,
    • 类型检查,
    • 尺寸检查。

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

    【讨论】:

      【解决方案2】:

      实施自定义检查,以下是 Play 文档中的示例:

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

      以下是 Lunatech 关于使用 Play 上传文件的精彩帖子的链接: http://www.lunatech-research.com/playframework-file-upload-blob

      【讨论】:

      • 我看过这两个帖子。在这里发帖之前,我做了一些研究,你知道的。 ;) 另外,我的问题显然是针对“图像”上传验证的,而这两者都没有以任何方式回答我的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 2018-05-09
      • 2016-10-01
      • 2016-02-02
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多