I have a view scoped bean where I create a person. A person can have a picture. This picture is uploaded the same page the person is created. The picture is not stored in a
Add.xhtml
Here is Managed Bean Code:
@ManagedBean
@RequestScoped
public class ProductController implements Serializable{
private ProductBean bean;
@ManagedProperty(value = "#{ProductService}")
private ProductService productService;
private StreamedContent content;
private UploadedFile file;
public StreamedContent getContent() {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
}
else{
String imageId = context.getExternalContext().getRequestParameterMap().get("id");
Product product = getProductService().getProductById(Integer.parseInt(imageId));
return new DefaultStreamedContent(new ByteArrayInputStream(product.getProductImage()));
}
}
public ProductController() {
bean = new ProductBean();
}
public void setContent(StreamedContent content) {
this.content = content;
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void saveProduct(){
try{
Product product = new Product();
product.setProductImage(getFile().getContents());
getProductService().saveProduct(product);
file = null;
}
catch(Exception ex){
ex.printStackTrace();
}
}
public void validateFile(FacesContext ctx,
UIComponent comp,
Object value) {
List msgs = new ArrayList();
UploadedFile file = (UploadedFile)value;
int fileByte = file.getContents().length;
if(fileByte > 15360){
msgs.add(new FacesMessage("Too big must be at most 15KB"));
}
if (!(file.getContentType().startsWith("image"))) {
msgs.add(new FacesMessage("not an Image file"));
}
if (!msgs.isEmpty()) {
throw new ValidatorException(msgs);
}
}
}
Add these lines of code in web.xml
PrimeFaces FileUpload Filter
org.primefaces.webapp.filter.FileUploadFilter
PrimeFaces FileUpload Filter
Faces Servlet
And following jar files in WEBINF/lib folder.
commons-io-X.X and commons-fileupload-X.X, recommended most recent version.
commons-io-2.4,commons-io-2.4-javadoc,commons-io-2.4-sources,commons-io-2.4-tests,commons-io-2.4-test-sources,commons-fileupload-1.3,commons-fileupload-1.3-javadoc,commons-fileupload-1.3-sources,commons-fileupload-1.3-tests,commons-fileupload-1.3-test-sources
View.xhtml
#{products.productName}