Cannot convert class org.primefaces.model.file.UploadedFilesWrapper to interface org.primefaces.model.file.UploadedFile - jsf

I'm trying to upload files via primefaces 10.0.. I got the below error msg :
"Cannot convert org.primefaces.model.file.UploadedFilesWrapper#7200b7ba of type class org.primefaces.model.file.UploadedFilesWrapper to interface org.primefaces.model.file.UploadedFile"
code as below :
XHTML:
<h:form enctype="multipart/form-data">
<p:fileUpload uploadLabel="aa" cancelLabel="aa" value="#{managedBean.fileToUpload}"
mode="simple" skinSimple="true" multiple="true" />
<p:commandButton action="#{managedBean.uploadFileDone()}" value="upload" />
</h:form>
ManagedBean:
public void uploadFileDone(){
System.out.println(fileDetailActivite);
this.upload(fileDetailActivite,"Activite_"+activite.getId()+".pdf");
}
public void upload(UploadedFile file,String type) {
if (file != null) {
// System.out.println("FileUploadEvent");
String path = "C:\\tmp\\";
File dir = new File (path);
dir.mkdirs();
FacesMessage msg = new FacesMessage("Success! ", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
// Do what you want with the file
try {
InputStream
inputStream = file.getInputStream();
copyFile(file.getFileName(), inputStream,type);
} catch (IOException e) {
e.printStackTrace();
}
FacesMessage message = new FacesMessage("Successful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
public void copyFile(String fileName, InputStream in,String type) {
// System.out.println("copyFile");
try {
// write the inputStream to a FileOutputStream
fileName=" ";
// OutputStream out = new FileOutputStream(new File(destination + type+"_"+fileName));
OutputStream out = new FileOutputStream(new File(destination +type+""+fileName));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

When using multiple="true", you need a UploadedFiles property instead of a UploadedFile property so that it can hold multiple files instead of only one.
private UploadedFiles files;
<p:fileUpload value="#{bean.files}" multiple="true" />
Or, if that was not your intent, then you need to remove the multiple="true" attribute.
private UploadedFile file;
<p:fileUpload value="#{bean.file}" />

Related

Restricting file upload if image isn't attached

I have a jsf form that takes an email address, brief description, and image from the user. The else statement below is completely ignored when file==null. If a picture isn't uploaded I want an error telling the user they have to upload a image. How do I accomplish this?
import org.primefaces.model.UploadedFile;
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public String upload() {
if (file!=null ) {
try {
System.out.println(file.getFileName());
InputStream fin2 = file.getInputstream();
Connection con = DataConnect.getConnection();
PreparedStatement pre = con.prepareStatement("insert into PICTURE_TABLE (EMAIL_ADDRESS,PRICE,ITEM_DESC,PICTURES,DATE) values(?,?,?,?,?)");
pre.setString(1, email);
pre.setString(2, price);
pre.setString(3,itemDesc);
pre.setBinaryStream(4, fin2, file.getSize());
pre.setString(5,time);
pre.executeUpdate();
System.out.println("Inserting Successfully!");
}
catch (Exception e) {
System.out.println("Exception-File Upload." + e.getMessage());
return "imageFail";
}
}
else{
FacesMessage msg = new FacesMessage("Please select image!!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
this is the jsf tag I'm using.
<h:form enctype="multipart/form-data"

"Content-Disposition" Header shows wrong filename in dialog window "save as"

When I download a file, the filename that is display in the "save as" dialog window its the name of the view (Page2.pdf) and not the filename "cyn.pdf".
Header content disposition is on line 161 of FileUploadController and "download" its call on line 34 of Page2.xhtml
FileUploadController Bean
#ManagedBean(name = "fileUploadController")
#SessionScoped
public class FileUploadController implements Serializable {
private static final long serialVersionUID = 1L;
//tama�o del buffer
private static final int DEFAULT_BUFFER_SIZE = 10240;
private byte[] archi = new byte[0];
public String nombre;
public String ruta;
public String nombreArchivo;
public byte[] getArchi() {
return archi;
}
public void setArchi(byte[] archi) {
this.archi = archi;
}
// Nombre del Archivo
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getRuta() {
return ruta;
}
public void setRuta(String ruta) {
this.ruta = ruta;
}
// ruta fisica del archivo
public String getRealPath() {
FacesContext aFacesContext = FacesContext.getCurrentInstance();
ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
return context.getRealPath("/");
}
/* subida del archivo con sus atributos */
public void fileUpload(FileUploadEvent event, String nombre, String type, String directorio) {
try {
this.nombre = "cyn" + type;
this.ruta = directorio + getNombre();
this.archi = getFileContents(event.getFile().getInputstream());
File file = new File(directorio);
nombreArchivo = file.getName();
// Crea el directorio, incluidos subdirectorios q no existan
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception ex) {
System.out.println("Error en la subida " + ex);
}
}
private byte[] getFileContents(InputStream in) {
byte[] bytes = null;
try {
// write the inputStream to a FileOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read = 0;
bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
bos.write(bytes, 0, read);
}
bytes = bos.toByteArray();
in.close();
in = null;
bos.flush();
bos.close();
bos = null;
} catch (IOException e) {
System.out.println(e.getMessage());
}
return bytes;
}
// Guardar el archivo
public void guardar() {
try {
FileOutputStream out;
out = new FileOutputStream(ruta);
System.out.print("out" + out);
out.write(archi);
System.out.print(archi);
out.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
/*-------------------- Servlet Descarga Archivos----------------------------------------------*/
public void downLoad() throws IOException, ServletException {
FacesContext contexto = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) contexto.getExternalContext().getResponse();
//ruta de los archivos
System.out.println("paso parametro ruta " + ruta);
File file = new File(ruta);
System.out.println("paso parametro ruta a file " + file);
/*Validacion*/
if (!file.exists()) {
System.out.println("El archivo no existe!");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("application/pdf");
response.setHeader("Content-Length", String.valueOf(file.length()));
/*Ventana de abrir/guardar*/
/*attachment: muestra la ventana*/
response.setHeader("Content-Disposition", "attachment; Nombre del Archivo=\"" + nombreArchivo + "\"");
System.out.println("NOmbre archivo en download" + nombreArchivo);
//inicializo el input y el output
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
//cierro
input.close();
output.close();
}
contexto.responseComplete();
}
}
View: Page2.xhtml
<h:body>
<h2>Acceso Alumno</h2>
<h1>Alumnos registrados </h1>
<h:form>
<h:dataTable id ="tabla" value ="#{alumno.getListaAlumno()}" var= "var" border="1">
<h:column>
<f:facet name="header">Id </f:facet>
<h:outputText value = "#{var.id}"/>
</h:column>
<h:column>
<f:facet name="header">Nombre y Apellidos </f:facet>
<h:outputText value = "#{var.nombreApellidos}"/>
</h:column>
<h:column>
<f:facet name="header">Matricula </f:facet>
<h:outputText value = "#{var.matricula}"/>
</h:column>
<h:column>
<f:facet name="header">ProductBox </f:facet>
<h:commandButton action="#{fileUploadController.downLoad}" value="Guardar Archivo" >
<f:setPropertyActionListener target="#{fileUploadController.ruta}" value="#{var.pdf}" />
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
<h:form>
<h:commandButton action="home?faces-redirect=true" value="Home" />
</h:form>
<!-- Cerrar Sesion -->
Cerrar Sesion
</h:body>
</html>
Try using the following Content-disposition
response.setHeader("Content-disposition", "attachment;filename=cyn.pdf");

rendered attribute not working with request parameter

I am using JSF2.2 with primefaces 5.0. I have a xhtml file where there are two file Uploads where one should always be visible while other should be visible only when request parameter, named signmethod, is JAVAME.
<h:panelGrid>
<h:panelGroup>
<h:outputLabel for="selected_signmethod" value="Selected Signethod : "/>
<h:outputText id="selected_signmethod" value="#{param.signmethod}" />
</h:panelGroup>
<h:panelGroup>
<b>Select file(s) to upload:</b>
</h:panelGroup>
</h:panelGrid>
<h:form id="uploadForm" enctype="multipart/form-data">
<p:message for="file_upload"/>
<p:fileUpload id="file_upload" allowTypes="#{fileUploadView.allowedTypes}" label="Select file" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" update="growl" multiple="true" fileLimit="5"/>
<p:message for="javame_upload"/>
<h:panelGroup rendered="#{param.signmethod == 'JAVAME'}" >
<b>Select corresponding jar file(s) to upload:</b>
<p:fileUpload id="javame_upload" allowTypes="" label="Select Jar file for javame" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" multiple="true" fileLimit="5"/>
</h:panelGroup>
<p:commandButton ajax="false" id="signProceed" value="Proceed" action="#{fileUploadView.submit}"/>
</h:form>
But this seems to be not happening. Second upload component is not getting rendered at all. I am also printing value of param.signmethod so that to be sure that right value is getting into param.signmethod, which is correct. So whats stopping this component to get rendered.
Managed Bean code :
#ManagedBean
#ViewScoped
public class FileUploadView implements Serializable {
#ManagedProperty(value = "#{signBundleBean}")
private SignBundleBean signBundleBean;
static String uploadDirRoot = InitialisationHelper.getUploadDirRoot();
transient Map<String, Object> sessionMap;
ArrayList<Signing> signings;
String username;
SignMethod signMethod;
public FileUploadView() {
System.out.println("NEW FileUploadView created.");
}
#PostConstruct
public void init() {
System.out.println("#POstConstruct FileuploadView");
System.out.println("signMethod : " + signMethod);
sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
signings = signBundleBean.getSignings();
username = (String) sessionMap.get("username");
}
public void handleFileUpload(FileUploadEvent e) {
String signId = "" + DatabaseHelper.genrateSigningId();
FacesContext ctx = FacesContext.getCurrentInstance();
UploadedFile uploadedFile = e.getFile();
String filename = uploadedFile.getFileName();
if (signId.equals("-1")) {
FacesMessage fm = new FacesMessage();
fm.setDetail("Database Connection not working. Please try later.");
fm.setSummary("DBConnection_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
//ctx.addMessage(null, fm);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
if (username == null) {
FacesMessage fm = new FacesMessage();
fm.setDetail("You are not in session to upload.");
fm.setSummary("Session_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
Signing sg;
sg = new Signing(signId, username, filename, signMethod, false);
signings.add(sg);
System.out.println("Signing added : " + sg);
signBundleBean.setMaxParameters(SignParametersInitialisation.getNumberOfParameters(signMethod));
try {
InputStream is = uploadedFile.getInputstream();
OutputStream os = new FileOutputStream(sg.getUploadfile());
byte[] bytes = new byte[1024];
int read = 0;
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
sg.setUploaded(true);
is.close();
os.close();
} catch (IOException ex) {
signings.remove(sg);
Logger.getLogger(FileUploadView.class.getName()).log(Level.SEVERE, null, ex);
}
FacesMessage fm = new FacesMessage();
fm.setDetail(filename);
fm.setSummary("FileUploaded");
fm.setSeverity(FacesMessage.SEVERITY_INFO);
//ctx.addMessage(null, fm);
ctx.addMessage(null, fm);
System.out.println(sg + " File uploaded to " + sg.getUploadfile());
}
}

JSF Primefaces pass parameter to fileupload

JSF 2.2 - Primefaces 4.0 - JBoss Wildfly
Hi, I am trying to pass a parameter value to the file upload handler.
I tried a few suggestions I found, but can't get it to work.
I stepped a few steps back
I need the #{fileUploadController.newItemId} in the controller
When going to the file update page it is done with i.e. this URL
/fileUpload.jsf?newItemId=10
I tried what it mentioned in
How to send parameter to fileUploadListener in PrimeFaces fileUpload
and
Passing value to the backing bean with PrimeFaces file upload
fileUpload.xhtml
<f:metadata>
<f:viewParam name="newItemId"
value="#{fileUploadController.newItemId}" />
<f:viewAction action="#{fileUploadController.loadData()}" />
</f:metadata>
<h:form id="item" enctype="multipart/form-data">
<p:messages id="messages" />
<p:panelGrid styleClass="panelGridCenter">
<p:row>
<p:column>
<p:fileUpload
fileUploadListener="#{fileUploadController.handleFileUpload}"
validator="#{fileUploadController.validateFile}" mode="advanced"
dragDropSupport="false" update="messages" sizeLimit="1000000"
fileLimit="100" allowTypes="/(\.|\/)(gif|jpe?g|png)$/">
</p:fileUpload>
</p:column>
</p:row>
</p:panelGrid>
</h:form>
FileUploadController.java
public void handleFileUpload(FileUploadEvent event) {
try {
// Need item id here :)
UploadedFile file = event.getFile();
InputStream inputStream = file.getInputstream();
FileOutputStream outputStream = new FileOutputStream(file.getFileName());
byte[] buffer = new byte[4096];
int bytesRead = 0;
while (true) {
bytesRead = inputStream.read(buffer);
if (bytesRead > 0) {
outputStream.write(buffer, 0, bytesRead);
} else {
break;
}
}
outputStream.close();
inputStream.close();
Long imageId = serviceSLSB.saveImage(itemId, file, buffer);
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded and saved with id." + imageId);
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (Exception e) {
String errorMessage = getRootErrorMessage(e);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Saving unsuccessful");
facesContext.addMessage(null, m);
}
}
public void loadData() {
if (newItemId == null) {
String message = "Bad request. Please use a link from within the system.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
return;
} else {
String message = "Your are adding images to item with id : " + newItemId;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
return;
}
}
I just found that my controller was only request scoped, after changing it to
#ViewScoped
#Named
public class FileUploadController implements Serializable
I of cause still have the item id, and can now add images to that item.
Thanks for the comments guys

Navigation to call action for bean class

I am using JSF 2.0 and PrimeFaces 3.0. I have uploaded the images and have to crop the image. The images are uploaded and successfully displayed in the upload pages.
When I select the images and click the crop button the corresponding crop bean is not called. If I don't select the image and click the crop button the corresponding crop bean class is called but a NullPointerException occurred. What is the problem?
The Facelet view is:
<h:form>
<p:panel header="FILE UPLOAD WITH CROPPER" style="width:900px; margin: 0 auto; margin-top:0px">
<p:fileUpload fileUploadListener="#{photoUploadAction.handleImageUpload}"
mode="advanced"
update="getImageId,messages" auto="false"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<p:growl id="messages" showDetail="true"/>
<p:growl id="uploadMessages" showSummary="true" showDetail="true"/>
<h:panelGrid columns="2" >
<p:imageCropper value="#{photoUploadAction.croppedImage}" id="getImageId"
image="images/#{photoUploadVO.imageName}"/>
</h:panelGrid>
<p:commandButton value="Crop" update="getImageId" action="#{imageCropperBean.crop}" />
</p:panel>
</h:form>
BACKING BEAN for ImageCropper:
#ManagedBean(name="imageCrop")
#RequestScoped
public class ImageCropperBean {
private CroppedImage croppedImage;
private String newFileName;
private String imageName;
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
System.out.println("TEH IMAGE NAME ===="+imageName);
this.imageName = imageName;
}
public String getNewFileName() {
return newFileName;
}
public void setNewFileName(String newFileName) {
System.out.println("AAAAAAAAAAAAAA"+this.newFileName);
this.newFileName = newFileName;
}
public CroppedImage getCroppedImage() {
return croppedImage;
}
public void setCroppedImage(CroppedImage croppedImage) {
System.out.println("cRRRRRRRRRRRRR"+croppedImage);
this.croppedImage = croppedImage;
}
public ImageCropperBean(){
}
public String crop() {
System.out.println("WELCOMEMMMMMMMMMMMMMM");
FacesContext context = FacesContext.getCurrentInstance();
ImageCropperBean imageCropperBean = (ImageCropperBean) context.getApplication().evaluateExpressionGet(context, "#{imageCropperBean}", ImageCropperBean.class);
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
newFileName = servletContext.getRealPath("") + File.separator + "cropImage" + File.separator+ "croppedImage.jpg";
System.out.println("FILE NAME NAME NAME NAME "+newFileName);
String file = new File(newFileName).getName();
System.out.println("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"+file);
imageCropperBean.setImageName(file);
File fileFolder = new File("e:/Mecherie_project/image_web/WebContent/cropImages",file);
System.out.println("FILE ANE"+file);
// String target=null;
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(fileFolder);
System.out.println("HHHHHHHHHH=="+imageOutput);
imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
imageOutput.close();
FacesMessage msg = new FacesMessage("Succesful", file
+ " is cropped.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (FileNotFoundException e) {
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not Cropped!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not Cropped!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
}
// System.out.println("ghfhgfghgh"+target);
return "success";
}
}

Resources