Steve Knight wrote:
> Are there any examples of how I can validate an uploaded file? For
> example, I would like to validate that the user uploaded a valid image
file.
Here's a validator I use (formatting mangled). One weird thing you
probably don't need is the part where it writes a file and deletes it;
that's for when the upload directory isn't always writable.
Nathan
--------
public class ImageValidator extends AbstractValidator {
private int width = 0, height = 0;
private String extension;
/**
* Create a validator with width and height constraints.
*/
public ImageValidator(int width, int height) {
this.width = width;
this.height = height;
}
/**
* @param width required width in pixels
* @param height required height in pixels
* @param extension required extension (without period)
*/
public ImageValidator(int width, int height, String extension) {
this(width, height);
this.extension = "." + extension.toLowerCase();
}
public void validate(FormComponent component) {
FileUploadField fu = (FileUploadField) component;
if (fu.getFileUpload() != null) {
try {
BufferedImage image =
ImageIO.read(fu.getFileUpload().getInputStream());
if (image == null || (extension != null &&
fu.getFileUpload().getClientFileName().toLowerCase().endsWith(extension)))
error(fu, "ImageValidator.formatError",
Collections.EMPTY_MAP);
else if ((width > 0 && image.getWidth() != width) ||
(height > 0 && image.getHeight() != height))
error(fu, "ImageValidator.sizeError",
Collections.EMPTY_MAP);
else {
// try making a file to fail validation if not on upload
// server
File testFile = new
File(FileUtil.getFullPath("/content/" + RandomUtil.randomString(10)));
if (testFile.createNewFile()) testFile.delete();
}
} catch (IOException e) {
error(fu, "ImageValidator.ioError", Collections.EMPTY_MAP);
}
}
}
}
-------------------------------------------------------------------------
Take Surveys. Earn Cash. Influence the Future of IT
Join SourceForge.net's Techsay panel and you'll get the chance to share your
opinions on IT & business topics through brief surveys -- and earn cash
http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV
_______________________________________________
Wicket-user mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/wicket-user