I try to make a simple fileupload so:
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{catastrofes.file}" mode="simple"></p:fileUpload>
<p:separator/>
<h:commandButton value="Dummy Action" action="#{catastrofes.dummyAction}" ajax="false"></h:commandButton>
</h:form>
But when I submit, get file = null and raise NullPointerException, here a similar question, but the answer don't work for me, any ideas?
Here my managed bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.primefaces.model.UploadedFile;
#ManagedBean(name="catastrofes")
#RequestScoped
public class CatastrofesBean {
private UploadedFile file;
public String dummyAction() {
System.out.println("Uploaded File Name Is :: " + file.getFileName() + " :: Uploaded File Size :: " + file.getSize());
return "";
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
}
And my web.xml:
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto|native|commons</param-value>
</context-param>
<filter>
<filter-name>Primefaces FileUpload Filter</filter-name>
<filter-class>
org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>Primefaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
Thanks!
According to primefaces_user_guide
auto: This is the default mode and PrimeFaces tries to detect the best method by checking the
runtime environment, if JSF runtime is at least 2.2 native uploader is selected, otherwise commons.
native: Native mode uses servlet 3.x Part API to upload the files and if JSF runtime is less than 2.2
and exception is being thrown.
commons: This option chooses commons fileupload regardless of the environment, advantage of
this option is that it works even on a Servlet 2.5 environment.
You should choose only one option not paste all those three options.
If you have commons-fileupload library in your project, I suggest you to choose commons.
in web.xml
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
xhtml
<h:form enctype="multipart/form-data">
<p:growl id="messages" showDetail="true" />
<p:fileUpload value="#{fileUploadView.file}" mode="simple" />
<br /> <br />
<h:commandButton value="Dummy Action"
action="#{fileUploadView.upload}">
</h:commandButton>
</h:form>
managedbean
#ManagedBean
#RequestScoped
public class FileUploadView {
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void upload() {
System.out.println("Uploaded File Name Is :: " +
file.getFileName() +
" :: Uploaded File Size :: " + file.getSize());
if(file != null) {
FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
}
Related
This question already has answers here:
How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable
(11 answers)
Closed 6 years ago.
The UploadedFile is null when I clicked the commandButton. What's Wrong?
in the form tag i insert the code : enctype="multipart/form-data"
<h:form enctype="multipart/form-data">
<p:fileUpload mode="simple" value="#{b_cargar_tbl.file}" />
<p:commandButton actionListener="#{b_cargar_tbl.upload()}" value="Send" ajax="false" />
</h:form>
The code of bean is:
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void upload() {
if(file != null) {
FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
The web.xlm
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto|native|commons</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
this solution:
add atribute fileUploadListener into p:fileUpload and create in your managedbean class method with one parametr listener FileUploadEvent
example:
<p:commandButton actionListener="#{b_cargar_tbl.upload()}" value="Send"
fileUploadListener="#{b_cargar_tbl.upload}" ajax="false" />
in your managed bean add method:
public void upload(FileUploadEvent event) {
System.err.println("event.getFile().getFileName() = " + event.getFile().getFileName());
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (Exception ex) {
ex.printStackTrace();
}
}
When using fileUpload from primefaces5.0, the file uploaded is always null.
The View :
<h:form enctype="multipart/form-data" style="text-align:center;">
<p:fileUpload value="#{noteController.fileName}" mode="simple" skinSimple="true" />
<p:commandButton class="btn btn-success" value="Upload file" ajax="false" actionListener="#{noteController.upload}" />
</h:form>
ManagedBean :
#ManagedBean( name = "noteController")
#ApplicationScoped
public class NoteController {
private UploadedFile fileName;
public String upload(){
if(fileName != null) {
return "success";
}
return "error";
}
public UploadedFile getFileName() {
return fileName;
}
public void setFileName(UploadedFile fileName) {
this.fileName = fileName;
}
}
And the web.xml, I add this :
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>
org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
As result : fileName is always null, and the view is not redirected to the error's view. The view remains at the same page when the action upload is trigged.
Remove skinSimple="true", this worked for me.
Anyhow, still trying to find the reason...
I have a fileUpload in multiple mode:
<p:fileUpload fileUploadListener="#{perosnaDesapBean.handleFileUpload}" mode="advanced" dragDropSupport="false"
multiple="true" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
label="Elegir Imágenes"
cancelLabel="Cancelar"
uploadLabel="Subir"
update="messages"
/>
And in my managed bean had the handle:
public void handleFileUpload(FileUploadEvent event) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
For the first uploaded file show the message, but for the second one nothing. It runs the event handler once.
My web.xml file:
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
My managed bean is #ConversationScoped, may be why? I'm using PF: 5.1
Thanks.
Example: PF 5.1, JSF 2.2, commons-io-2.4, commons-fileupload-1.3.1
Class definition:
#ManagedBean ( name="fileUploadManagedBean" )
#SessionScoped
public class FileUploadManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
private UploadedFile fileImage;
public UploadedFile getFileImage() {
return fileImage;
}
public void setFileImage(UploadedFile fileImage) {
this.fileImage = fileImage;
}
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile()
.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
XHTML definition:
<h:form enctype="multipart/form-data" >
<p:growl id="msg" />
<p:fileUpload value="#{fileUploadManagedBean.fileImage}"
invalidSizeMessage="Size off"
invalidFileMessage="Type off"
fileLimitMessage="Only 4 files"
mode="advanced" multiple="true" fileLimit="4" sizeLimit="1951200"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
fileUploadListener="#{fileUploadManagedBean.handleFileUpload}"
update="msg" />
</h:form>
WEB.XML definition
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>
org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>1951200</param-value>
</init-param>
<init-param>
<param-name>uploadDirectory</param-name>
<param-value>/tmpImages</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
I am using the Primefaces 5.0 file uploaded with the Apache Commons Uploader. The control appears on the web page and I can select a file, but when I click a button to action it the file object in the controller has not been set.
The web page:
<h:form id="master">
<p:panelGrid columns="2">
<p:fileUpload value="#{controller.file}" mode="simple"/>
<p:commandButton value="Upload"
ajax="false" actionListener="# {controller.uploadFile}" />
</p:panelGrid>
Controller:
#ManagedBean
#ViewScoped
public class Controller implements Serializable {
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void uploadFile() {
if(file != null) {
//Doesn't get here because file is null
}
}
web.xml
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>common</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>
org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
I tried setting the File Uploader to "auto" in the web.xml, but then I get multi-part exceptions which I couldn't resolve.
You miss to use enctype="multipart/form-data" in <h:form>. Change as below
<h:form enctype="multipart/form-data">
...
</h:form>
What does enctype='multipart/form-data' mean?
In RichFaces, inorder to upload a file I used rich:fileUpload. By using rich:fileUpload Add, Upload and Clear All buttons are automatically generating in the richfaces livedemo example but for me Add, Upload and Clear All are appearing as text in my browser where should I change so that Add,upload and clearAll can be clickable. Do I have to change any settings in web.xml / pom.xml file.
I am using RichFaces 4 and JSF 2.
This is my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Sample RichFaces 4 Application</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>#{skinBean.skin}</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.fileUpload.maxRequestSize</param-name>
<param-value>1000000000</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.fileUpload.createTempFiles</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<mime-mapping>
<extension>ecss</extension>
<mime-type>text/css</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>index.jsf</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
Hi, i am getting those add and update buttons now correctly by simply providing h:head and h:body tags but i am getting this exception javax.faces.event.AbortProcessingException and files are not being uploaded as shown in the example provided in the link "FileUpload example".Can anyone plz help me out from this issue
This is my xhtml page
<!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:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich">
<ui:composition>
<h:head>
<h:outputStylesheet>
.top {
vertical-align: top;
}
.info {
height: 202px;
overflow: auto;
}
</h:outputStylesheet>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2" columnClasses="top,top">
<rich:fileUpload fileUploadListener="#{fileUploadBean.listener}" id="upload" acceptedTypes="jpg, gif, png, bmp"
ontyperejected="alert('Only JPG, GIF, PNG and BMP files are accepted');" maxFilesQuantity="5">
<a4j:ajax event="uploadcomplete" execute="#none" render="info" />
</rich:fileUpload>
<h:panelGrid id="info" layout="block">
<rich:panel bodyClass="info">
<f:facet name="header">
<h:outputText value="Uploaded Files Info" />
</f:facet>
<h:outputText value="No files currently uploaded" rendered="#{fileUploadBean.size==0}" />
<rich:dataGrid columns="1" value="#{fileUploadBean.files}" var="file" rowKeyVar="row">
<rich:panel bodyClass="rich-laguna-panel-no-header">
<h:panelGrid columns="2">
<a4j:mediaOutput element="img" mimeType="image/jpeg" createContent="#{fileUploadBean.paint}"
value="#{row}" style="width:100px; height:100px;" cacheable="false">
<f:param value="#{fileUploadBean.timeStamp}" name="time" />
</a4j:mediaOutput>
<h:panelGrid columns="2">
<h:outputText value="File Name:" />
<h:outputText value="#{file.name}" />
<h:outputText value="File Length(bytes):" />
<h:outputText value="#{file.length}" />
</h:panelGrid>
</h:panelGrid>
</rich:panel>
</rich:dataGrid>
</rich:panel>
<br/>
<a4j:commandButton action="#{fileUploadBean.clearUploadData}" render="info, upload" value="Clear Uploaded Data"
rendered="#{fileUploadBean.size>0}" />
</h:panelGrid>
</h:panelGrid>
</h:form>
</h:body>
</ui:composition>
</html>
This is my FileUploadBean Class
package com.acc.upload;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import com.acc.fileupload.utils.FileUploadEvent;
import com.acc.fileupload.utils.UploadedFile;
#ManagedBean(name = "fileUploadBean")
#SessionScoped
public class FileUploadBean{
private ArrayList<File> files = new ArrayList<File>();
private int uploadsAvailable = 5;
private boolean autoUpload = false;
private boolean useFlash = true;
public int getSize() {
if (getFiles().size()>0){
return getFiles().size();
}else
{
return 0;
}
}
public FileUploadBean() {
}
public void paint(OutputStream stream, Object object) throws IOException {
stream.write(getFiles().get((Integer)object).getData());
}
public void listener(FileUploadEvent event) throws Exception{
UploadedFile item = event.getUploadedFile();
File file = new File();
file.setLength(item.getData().length);
file.setName(item.getName());
file.setData(item.getData());
files.add(file);
uploadsAvailable--;
}
public String clearUploadData() {
files.clear();
setUploadsAvailable(5);
return null;
}
public long getTimeStamp(){
return System.currentTimeMillis();
}
public ArrayList<File> getFiles() {
return files;
}
public void setFiles(ArrayList<File> files) {
this.files = files;
}
public int getUploadsAvailable() {
return uploadsAvailable;
}
public void setUploadsAvailable(int uploadsAvailable) {
this.uploadsAvailable = uploadsAvailable;
}
public boolean isAutoUpload() {
return autoUpload;
}
public void setAutoUpload(boolean autoUpload) {
this.autoUpload = autoUpload;
}
public boolean isUseFlash() {
return useFlash;
}
public void setUseFlash(boolean useFlash) {
this.useFlash = useFlash;
}
}
File Class
package com.acc.upload;
public class File {
private String Name;
private String mime;
private long length;
private byte[] data;
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
int extDot = name.lastIndexOf('.');
if(extDot > 0){
String extension = name.substring(extDot +1);
if("png".equals(extension)){
mime="image/png";
}else {
mime = "img/unknown";
}
}
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public String getMime(){
return mime;
}
}
Thanks a lot.Now that error is gone for me .
I set the createTemp files to true in web.xml but i am unable to find the uploaded file in the temp folder in my local system.And also is it possible to store the uploaded file to a desired location in our local system by changing any settings in web.xml file ?
Please help in these two issues.
Regarding your buttons icons problem, I'm pretty sure you don't manage yourself the skin of RichFaces, so you can remove this from your web.xml :
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>#{skinBean.skin}</param-value>
</context-param>
RichFaces will now use the default skin option.
According to your comment, you where missing h:head which is mandatory in order to include necessary resources CSS and JavaScript for RichFaces.
Moreover, your last problem is related to your imports that are bad :
import com.acc.fileupload.utils.FileUploadEvent;
import com.acc.fileupload.utils.UploadedFile;
should be replaced for :
import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;
Other info :
The example you are based on is from RichFaces 3.3.3 (this is shown in the footer). Double check your view code with this example for RichFaces 4.3.2.
I also get this problem with richface 4.0.0 and spring 4. When upload the file I alway get this error message "Request prolog cannot be read".
And I solved this problem by: set multipart resolever to
instead of CommonsMultipartResolver
for DispatcherServlet. Because the CommonsMultipartResolver of spring is not consistent with richface 4.0.0
Hope this help!