How to import file in a directory using jsf - java

Hi all I'm new to Java development, and I'm really confused about this.
im doing an web app and my problem is how to import file and put it in i directory. i have created the xhtml file :
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:jsf="http://xmlns.jcp.org/jsf"
xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
xmlns:p="http://primefaces.org/ui"
template="/WEB-INF/template/template.xhtml">
<ui:define name="title">2G</ui:define>
<ui:define name="content">
<h:form>
<h1> <font color="orange" size="7" > 2G</font></h1>
</h:form>
<h2 >Choose 2 files </h2>
<h:form>
<p:fileUpload fileUploadListener="#{import_2G.save()}"
mode="advanced" dragDropSupport="true" update="messages"
sizeLimit="100000000000" allowTypes="/(\.|\/)(xls)$/" />
<p:growl id="messages" showDetail="true" />
</h:form>
</ui:define>
</ui:composition>
and this is the bean file :
#ManagedBean
#RequestScoped
public class Import_2G {
public Import_2G() { }
#EJB
private GestionCellRef2GLocal gestionCellRef2GLocal;
private UploadedFile uploadedFile;
public void save() throws IOException {
GestionCellRef2GRemote t = null;
Path folder = Paths.get("C:\\Upload");
String filename = FilenameUtils.getBaseName(uploadedFile.getFileName());
String extension = FilenameUtils.getExtension(uploadedFile.getFileName());
Path file = Files.createTempFile(folder, filename + "-", "." + extension);
if (file != null) {
FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " was uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
try (InputStream input = uploadedFile.getInputstream()) {
Files.copy(input, folder, StandardCopyOption.REPLACE_EXISTING);
}
}
}
any help guys ?

First start reading about naming conventions in Java. If you not respect the naming conventions and use underscores, scores and things like that, you will have some troubles.
Second, you forgot the enctype. When you wanna upload binary data, you must have put the attribute: enctype="multipart/form-data". Let's build a file upload.
First your form:
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{import2G.file}"
mode="advanced" dragDropSupport="true"
sizeLimit="100000000"
allowTypes="/(\.|\/)(xls)$/"
update="messages"
fileUploadListener="#{import2G.save}" />
</h:form>
<p:growl id="messages" showDetail="true" />
And your backing bean:
public void save(FileUploadEvent e) {
FileUpload file = event.getFile();
String fileName = file.getFileName();
String contentType = file.getContentType();
byte[] content = file.getContents();
saveFile(content);
}
private void saveFile(byte[] data) {
FileOutputStream fos = new FileOutputStream(DIR_NAME);
fos.write(data);
fos.close();
}
Look the listener in the form; use import2G.save instead import2G.save(), this because a FileUpload parameter is passed to the listener in runtime.

Related

FindComponent + set invalid challenge

I have a this simplified form to show the challenge:
It is a form with multiple tabs (2 in this MVCE).
My goal is to highlight both fields in case of validation failure (but only for tab it is failing for).
TabView (backing bean)
package betlista.so.pf.findComponent;
import com.sun.faces.component.visit.FullVisitContext;
import org.primefaces.PrimeFaces;
import org.springframework.stereotype.Component;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.component.visit.VisitResult;
import javax.faces.context.FacesContext;
import java.util.LinkedList;
import java.util.List;
#Component
public class TabView {
List<TabData> tabData = new LinkedList<>();
{
tabData.add(new TabData("name 1", "val1-a", null));
tabData.add(new TabData("name b", "val1-b", "val2-b"));
}
public List<TabData> getTabsData() {
return tabData;
}
public void save() {
boolean isValid = isValid();
if (isValid) {
// continue ...
}
}
private boolean isValid() {
boolean isOk = isOk();
if (isOk) {
return true;
}
FacesMessage message = new FacesMessage("Not saved!");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, message);
final UIViewRoot viewRoot = context.getViewRoot();
List<UIInput> componentList = new LinkedList<>();
viewRoot.visitTree(new FullVisitContext(context), new VisitCallback() {
#Override
public VisitResult visit(VisitContext context, UIComponent target) {
if (target != null) {
final String id = target.getId();
if ("val1".equals(id) || "val2".equals(id)) {
if (target instanceof UIInput) {
componentList.add((UIInput) target);
}
}
}
return VisitResult.ACCEPT;
}
});
for (UIInput uiInput: componentList) {
uiInput.setValid(false);
}
context.validationFailed();
PrimeFaces.current().ajax().update("form");
final UIComponent val1 = context.getViewRoot().findComponent("val1");
return false;
}
private boolean isOk() {
return false;
}
}
in this simplified version isOk() returns false.
In a validation I know whether data for 1st or second tab is not ok and I'm trying to find a way how to highlight those two fields in tab.
I tried initially context.getViewRoot().findComponent(...), but I'm not able to "find it" (returns null). So to have access to the components I used this:
List<UIInput> componentList = new LinkedList<>();
viewRoot.visitTree(new FullVisitContext(context), new VisitCallback() {
#Override
public VisitResult visit(VisitContext context, UIComponent target) {
if (target != null) {
final String id = target.getId();
if ("val1".equals(id) || "val2".equals(id)) {
if (target instanceof UIInput) {
componentList.add((UIInput) target);
}
}
}
return VisitResult.ACCEPT;
}
});
so I have (in this case) all 4 components (but let say only those for first tab are invalid).
I'm trying to find a way how to identified which component belong to which tab (not sure whether to rely on a an order in list).
I was trying dynamic ID's, but it's not working, e.g. I added tab name (tabName)as attribute and used
<p:inputText id="#{cc.attr.tabName}-val2" ... />
I found no way how to add some custom flag/attribute whatever to be able to link component to a tab.
I was reading that ID can be dynamic once I'd use EL custom function (I mean I can use concatenation), but I was not able to find a resource describing it (I have no web.xml).
Code is available in GitHub.
myTab.xhtml (custom component)
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"
xmlns:composite="http://java.sun.com/jsf/composite">
<composite:interface>
<composite:attribute name="data" required="true" type="betlista.so.pf.findComponent.TabData" />
</composite:interface>
<composite:implementation>
<div class="ui-g">
<div class="ui-g-12">
<div class="ui-g-6">
<p:outputLabel value="Val 1:"/>
</div>
<div class="ui-g-6">
<p:inputText id="val1" value="#{cc.attrs.data.val1}" widgetVar="#{cc.attrs.data.tabName}-val1"/>
</div>
</div>
<div class="ui-g-12">
<div class="ui-g-6">
<p:outputLabel value="Val 2:"/>
</div>
<div class="ui-g-6">
<p:inputText id="val2" readonly="true" value="#{cc.attrs.data.val2}" widgetVar="#{cc.attrs.data.tabName}-val2"/>
</div>
</div>
</div>
</composite:implementation>
</html>
page.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:comp="http://xmlns.jcp.org/jsf/composite/comp">
<h:head>
<h:outputScript library="webjars" name="font-awesome/5.5.0/js/all.js"/>
</h:head>
<h:body styleClass="mainBody">
<h:form id="form">
<p:tabView id="tabView" value="#{tabView.tabsData}" var="tabVar">
<p:tab id="tab" title="#{tabVar.tabName}">
<comp:myTab data="#{tabVar}" />
</p:tab>
</p:tabView>
<p:commandButton value="Save" action="#{tabView.save()}" process="#form" update="#form" />
<p:growl id="growl" life="3000"/>
</h:form>
</h:body>
</html>
I got very confused by debugger...
The simplest solution is to add label like this:
<p:inputText id="val1" value="#{cc.attrs.data.val1}" label="someLabel1" />
...what I missed earlier is, that label is not a field therefor it was difficult to find it, it is available under stateHelper:
Probably better solution (despite label I cannot see in generated HTML) is to use custom attribute like this (I'd bet I tried that as well, apparently not):
<p:inputText id="val2" readonly="true" value="#{cc.attrs.data.val2}">
<f:attribute name="someAttribute" value="value2" />
</p:inputText>
and it's easily accessible:

Message: Missing PDF in PrimeFaces Extnsions DocumentViewer

I have problem to display StreamedContent PDF in DocumentViewer from Primefaces Extensions (6.2.9) with PrimeFaces 6.2 and MyFaces 2.2.12. I read the same question, but it's an other situation.
Message: Missing PDF in PrimeFaces Extensions DocumentViewer
This is my xhtml code
<p:commandButton icon="fa fa-print" actionListener="#{bean.onPrerender}" />
Dialog code
<p:dialog id="dvDialog" widgetVar="dv_dialog" dynamic="true" header="Document" width="1200px" height="700px" modal="true">
<pe:documentViewer cache="true" height="500" value="#{bean.content}" download="report.pdf" />
</p:dialog>
This is my java code
private StreamedContent content;
public void onPrerender(ActionEvent actionEvent) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, out);
document.open();
for (int i = 0; i < 50; i++) {
document.add(
new Paragraph("All work and no play makes Jack a dull boy"));
}
document.close();
// content = new DefaultStreamedContent(
// new ByteArrayInputStream(out.toByteArray()), "application/pdf");
content = new ByteArrayContent(out.toByteArray(), "application/pdf");
} catch (Exception e) {
e.printStackTrace();
}
PrimeFaces.current().executeScript("PF('dv_dialog').show()");
}
public StreamedContent getContent() {
return content;
}
public void setContent(StreamedContent content) {
this.content = content;
}
The error message
PDF.js v1.10.88 (build: c62a1938)
Message: Missing PDF "http://localhost:8080/hoft/javax.faces.resource/dynamiccontent.properties.xhtml?ln=primefaces&v=6.2&pfdrid=1a55ef4c9448951fae5f493579cf80e1&pfdrt=sc&pfdrid_c=true&download=report.pdf".
have anyone clue, what is wrong with my code? it is actually the code in demo showcase Primeface-Extensions with modification.
My project use iframe and the documentviewer will display in a popup dialog. I also tried with #SessionScoped and #ViewScoped, but have no luck.
If I try it in stand alone project, it works (without iframe). May be someone can give clues, how to debug to find the problem.
Please help.... Thank you.
I get error message
pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:17581 GET http://localhost:8081/hoft/javax.faces.resource/dynamiccontent.properties.xhtml?ln=primefaces&v=6.2&pfdrid=3c954d24c76c30714a581092c23e1489&pfdrt=sc&pfdrid_c=true&download=report.pdf 404
PDFFetchStreamReader # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:17581
getFullReader # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:17527
(anonymous) # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:4388
(anonymous) # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1002
resolveCall # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1001
_createStreamSink # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1266
MessageHandler._onComObjOnMessage # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1094
pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:19633 Uncaught (in promise) Error: Missing PDF file.
at pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:19633
I tried this using:
Java EE 7
GlassFish 4.1.2
PrimeFaces 6.2
PrimeFaces-Extensions 6.2.9
At the bean (class) code:
#ManagedBean
#ApplicationScoped
public class DocumentViewerController {
The scope is #ApplicationScoped. I have a private StreamedContent attribute. And two main public methods:
First method: It's called from actionListener attribute of a p:commandButton. The method receive a parameter (in my case).
public void onPrerender(Tramite tramite) {
tramiteSelected = tramite;
numeroTramite = tramite.getNumero();
contrato = tramite.getContrato();
}
Second method: It's used from a pe:documentViewer inside a dialog component, like this:
<pe:documentViewer id="certificadoViewer"
height="500px"
width="750px"
cache="false"
value="#{documentViewerController.certificado}"
download="certificado_#{documentViewerController.numero}_#{documentViewerController.contrato}.pdf" />
Note: The 2nd method works like a property (getter and setter). THAT'S THE TRICK.
The final code from my project is:
# Bean (DocumentViewerController.java):
package com.epmrpsd.certificado.consulta.controladores;
import com.epmrpsd.certificado.consulta.controladores.util.JsfUtil;
import com.epmrpsd.certificado.consulta.entidades.Tramite;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
/**
*
* #author pbonilla
*/
#ManagedBean
#ApplicationScoped
public class DocumentViewerController {
private StreamedContent content;
private Integer numeroTramite;
private Integer contrato;
private Tramite tramiteSelected;
// Path where the file exists
private String pdfPathDirectory = "C:\\Users\\<user>\\certificados\\";
public void onPrerender(Tramite tramite) {
tramiteSelected = tramite;
numeroTramite = tramite.getNumero();
contrato = tramite.getContrato();
}
public StreamedContent getCertificado() {
InputStream stream = null;
try {
File file = new File(pdfPathDirectory + numeroTramite + "_" + contrato + ".pdf");
if (file.exists()) {
stream = new FileInputStream(file);
} else {
JsfUtil.addErrorMessage("Error", "No se ha encontrado el archivo");
}
this.content = new DefaultStreamedContent(stream, "application/pdf");
} catch (FileNotFoundException fnfex) {
JsfUtil.addErrorMessage("Error", "No se ha encontrado el archivo. Error: " + fnfex.getMessage());
fnfex.printStackTrace();
} catch (Exception e) {
JsfUtil.addErrorMessage("Error", "Se ha generado un error al cargar el certificado. Error: " + e.getMessage());
e.printStackTrace();
}
return content;
}
public void setCertificado(StreamedContent contenido) {
content = contenido;
}
public Tramite getTramiteSelected() {
return tramiteSelected;
}
public void setTramiteSelected(Tramite tramiteSelected) {
this.tramiteSelected = tramiteSelected;
}
public Integer getNumero() {
return numeroTramite;
}
public void setNumero(Integer numeroTramite) {
this.numeroTramite = numeroTramite;
}
public Integer getContrato() {
return contrato;
}
public void setContrato(Integer contrato) {
this.contrato = contrato;
}
}
# View (index.xhtml):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:pe="http://primefaces.org/ui/extensions">
<h:head>
<title>Consulta de Certificados Digitales</title>
<h:outputStylesheet library="css" name="epmrpsd.css" />
<h:outputStylesheet library="webjars" name="font-awesome/5.5.0/css/all-jsf.css" />
<h:outputStylesheet library="css" name="jsfcrud.css"/>
<h:outputScript library="js" name="jsfcrud.js"/>
<link rel="shortcut icon" type="image/png" href="#{resource['images/logo.png']}"/>
</h:head>
<h:body>
<div id="background" style="position: fixed;">
<h:form id="formCertificados">
<div class="ui-g" style="margin-top: 25px;">
<div class="ui-g-1"></div>
<div class="ui-g-10">
<p:growl id="mensajes" />
<Extra code> ...
<p:outputPanel id="pnlCertificado">
<p:dataTable id="tramitesTable"
value="#{tramiteController.items}"
var="tramite"
rowKey="#{tramite.id}"
selectionMode="single"
selection="#{tramiteController.selected}"
emptyMessage="No se encontraron trámites con los criterios dados"
rows="10"
rowsPerPageTemplate="10,20,30,40,50">
<p:column headerText="Número Trámite" >
<h:outputText value="#{tramite.numero}" />
</p:column>
<p:column headerText="Descripción" >
<h:outputText value="#{tramite.tipo.descripcion}" />
</p:column>
<p:column headerText="Número Contrato" >
<h:outputText value="#{tramite.contrato}" />
</p:column>
<p:column style="text-align: center" headerText="Acción" >
<center>
<p:commandButton id="viewCertificado"
styleClass="ui-priority-primary"
value="Ver certificado"
actionListener="#{documentViewerController.onPrerender(tramite)}"
update=":ViewCertificadoForm"
oncomplete="PF('ViewCertificadoDialog').show()" />
</center>
</p:column>
</p:dataTable>
</p:outputPanel>
</div>
<div class="ui-g-1"></div>
</div>
</h:form>
<ui:include src="ViewCertificado.xhtml"/>
</div>
</h:body>
</html>
And the final component for the view is (ViewCertificado.xhtml):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions">
<ui:composition>
<p:dialog id="ViewCertificadoDlg"
widgetVar="ViewCertificadoDialog"
modal="true"
resizable="false"
appendTo="#(body)"
header="Certificado #{documentViewerController.contrato}">
<h:form id="ViewCertificadoForm">
<h:panelGroup id="display">
<p:panelGrid columns="1" rendered="#{documentViewerController.tramiteSelected != null}">
<pe:documentViewer id="certificadoViewer"
height="500px"
width="750px"
cache="false"
value="#{documentViewerController.certificado}"
download="certificado_#{documentViewerController.numero}_#{documentViewerController.contrato}.pdf" />
</p:panelGrid>
<p:commandButton value="Cerrar" onclick="ViewCertificadoDialog.hide()"/>
</h:panelGroup>
</h:form>
</p:dialog>
</ui:composition>
</html>

Upload file with java servlet results in resource not found

I have a source I think should work but for some reason it gives me resource not found and a completely different resource.
HTML part, just simple form:
<html lang="en">
<head>
<title>File Uploader</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="upload" enctype="multipart/form-data" >
File:
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>
Java part:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
#WebServlet(name = "FileUploader", urlPatterns = "upload")
#MultipartConfig
public class FileUploader extends HttpServlet {
private final static String serverPath = "/fileuploads";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
final Part filePart = request.getPart("file");
String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(serverPath + File.separator + fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + serverPath);
} catch (FileNotFoundException fne) {
writer.println("Missing file or no insufficient permissions.");
writer.println(" ERROR: " + fne.getMessage());
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(Part filePart) {
String header = filePart.getHeader("content-disposition");
String name = header.substring(header.indexOf("filename=\"")+10);
return name.substring(0, name.indexOf("\""));
}
}
I would expect the file to be uploaded to /proj/publ/fileuploads but insted it tells me that the resource /proj/publ/uploads is not available....
The files are in /proj/publ/ folder. Why is it always pointing to that folder that does not exist?
Thank you for your help.
Viking
EDIT: Prob is solved... for some reason I created the java file in src and not in WEB-INF/src... so there was the problem.
The resource is not available because the servlet is not mapped to any URL pattern. This can be done either by XML declaration in /WebContent/WEB-INF/web.xml or by #WebServlet annotation.
I see that you already use #WebServlet so you have to add urlPatterns element. Something like this:
#WebServlet(urlPatterns = "upload", name="FileUploader")
Another thing to solve is the form's action attribute. Based on the servlet container and its configuration the resource won't be available at the root of the container. It usually is in the form of host:port/application-context/url-pattern however this is not a strict rule. To avoid constant changes what is the right URL you can use JSTL's url tag. Something like this:
form method="POST" action="<c:url ='/upload' />" enctype="multipart/form-data" >
basically resource not found is when the file we are trying to request is not found or the path of resource is not there.
In your case please declare urlPattern in the webServlet annotation like this.
#WebServlet(urlPatterns="/upload")
#WebServlet[https://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebServlet.html]

Unable to load the image dynamically in jsf

I am working on some project, and i need to implement the image upload and view the image functionality,
but i am facing some problem here.
I am unable to display the image, can you please help me.
I am using p:fileload from primefaces, And i am storing all the images in bin folder of jboss server(E:\jboss-as-7.1.1.Final\bin\BrandImages\logo.gif).
And storing that path in MYSQL DB, till now it is working fine. But when i am trying to display the image by calling getBrandDetails(), it is unable to display. Can you please tell me how can i solve this problem???
In web.xml
In web.xml i added filter and mime...
Xhtml
<h:form enctype="multipart/form-data">
<h:panelGrid id="brandDetails_Panel" columns="2" columnClasses="plabel, pvalue" styleClass="ui-panelgrid">
<h:outputLabel for="brand_img_url" value="Brand Image" />
<p:fileUpload id="brand_img_url" fileUploadListener="#{brandBean.handleFileUpload}"
mode="advanced" sizeLimit="100000" allowTypes="/(\.\/)(gif|jpe?g|png)$/"/>
<h:outputLabel value="" />
<p:graphicImage value="#{brandBean.brand_image}" alt="The image could not be found."/>
</h:panelGrid>
<f:facet name="footer" >
<center>
<p:commandButton id="add" value="Add" disabled="#{brandBean.disable_addBut}" actionListener="#{brandBean.addBrandDetails}"/>
<p:commandButton id="view" value="View" disabled="#{brandBean.disable_viewBut}" action="#{brandBean.getBrandDetails}"/>
</center>
</f:facet>
</h:form>
In addBrandDetails(), handleFileUpload() as
public void handleFileUpload(FileUploadEvent event)
{
String t1=".\\BrandImages\\"+event.getFile().getFileName();
System.out.println("The final path is :"+t1);
try{
File f =new File(t1);
FileOutputStream fileOutputStream = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
}catch(Exception e)
{
System.out.println("Exception :"+e);
}
this.brand_image=t1;
}
In getBrandDetails(), i am setting as "this.setBrand_image(b.getBrand_img_url());"
When i am pringting it is printing path E:\jboss-as-7.1.1.Final\bin\BrandImages\logo.gif
but it is unable to display the image.
Please help me out....
First of all, your bean must have the scope as session. A good way is making just a bean for getting requested images.
Second, your varible "brand_image" need to be a object of DefaultStreamedContent. Because you are using primefaces.
brand_image = new DefaultStreamedContent(input, "image/jpeg");

Primefaces photoCam component not rendering

I am using primefaces photoCam component exactly as explained in
https://www.primefaces.org/showcase/ui/multimedia/photoCam.xhtml . unfortunately, unlike in the showcase my photoCam example, mine does not render. I have tried it on Firefox and Chrome the code is as follows:
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:form>
<h:panelGrid columns="3">
<p:photoCam widgetVar="pc" listener="#{photoCamBean.oncapture}" update="photos"/>
<p:commandButton type="button" value="Capture" onclick="pc.capture()"/>
<p:imageSwitch effect="zoom" id="photos">
<ui:repeat value="#{photoCamBean.photos}" var="photo">
<p:graphicImage value="/photocam/#{photo}.png" />
</ui:repeat>
</p:imageSwitch>
</h:panelGrid>
</h:form>
</ui:composition>
And the bean
#ManagedBean
#ViewScoped
public class PhotoCamBean {
private List<String> photos = new ArrayList<String>();
private String getRandomImageName() {
int i = (int) (Math.random() * 10000000);
return String.valueOf(i);
}
public List<String> getPhotos() {
return photos;
}
public void oncapture(CaptureEvent captureEvent) {
String photo = getRandomImageName();
this.photos.add(0,photo);
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
}
catch(Exception e) {
throw new FacesException("Error in writing captured image.");
}
}
}
The primefaces showcase photoCam renders a canvas with an adobe flash confirmation window but mine doesn't, what am i missing here?
Adding the meta tag in the head section of the page solves the problem as shown:
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</h:head>
<h:form>
<h:panelGrid columns="3">
<p:photoCam widgetVar="pc" listener="#{photoCamBean.oncapture}" update="photos"/>
<p:commandButton type="button" value="Capture" onclick="pc.capture()"/>
<p:imageSwitch effect="zoom" id="photos">
<ui:repeat value="#{photoCamBean.photos}" var="photo">
<p:graphicImage value="/photocam/#{photo}.png" />
</ui:repeat>
</p:imageSwitch>
</h:panelGrid>
</h:form>
</ui:composition>
I was able to view the canvas with an adobe flash confirmation window simply by adding the meta tag. Thank you all for your contribution.

Categories

Resources