Can we obtain dimensions of an image uploaded via <p:fileUpload>
in its listener based on org.primefaces.model.UploadedFile
in a JSF managed bean itself?
import java.io.IOException;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
public void fileUploadListener(FileUploadEvent event) throws IOException
{
UploadedFile uploadedFile = event.getFile();
//Do something to obtain the height and the width of the uploaded image here.
}
These dimensions can be obtained in various ways after storing the image on a disk like,
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
File file = new File("File path");
byte[] byteArray = IOUtils.toByteArray(uploadedFile.getInputstream());
// Or byte[] byteArray = uploadedFile.getContents();
FileUtils.writeByteArrayToFile(file, byteArray);
BufferedImage image=ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();
But can we obtain these dimensions before the file is actually stored on a disk so that it can be validated far before the service layer?
I'm currently using,
- PrimeFaces 4.0
- JSF 2.2.6
Writing images to a disk in a JSF managed bean is clumsy and cannot be done, since it requires much more code regarding file resize and many more. Moreover, files should only be written to a disk, if other information regarding that image is stored successfully into the database in question. Also, PrimeFaces file upload validators don't work.