Primefaces fileupload mode="Simple" with commandbutton ajax="true" throws nullpointer exception - file-upload

This is in reference to the following thread
[File upload doesn't work with AJAX in PrimeFaces 4.0/JSF 2.2.x - javax.servlet.ServletException: The request content-type is not a multipart/form-data
The problem I experience is Nullpointer on clicking the command button.
Starting from the web.xml
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
xhtml
<p:fileUpload id="file" value="#{userBean.uploadedFile}"
mode="simple" required="true" allowTypes="*.xls,*.xlsx"
requiredMessage="#{msg.vrUserUpload}"
invalidFileMessage="#{msg.vrUserUploadInvalidFile}"
multiple="false" fileUploadListener="userBean.fileUploadListener" />
<p:commandButton id="btnUpload" value="#{displayText.btUpload}"
styleClass="button_lite" actionListener="#{userBean.insert}"
ajax="true" update="userMassUploadForm"
process="userMassUploadForm">
</p:commandButton>
UserBean.java
public void fileUploadListener(FileUploadEvent event)
{
uploadedFile = event.getFile();
}
public void insert(){
if(uploadedFile!=null){
System.out.println(uploadedFile.getFileName());
}
else{
System.out.println("The file object is null.");
}
}
Console prints out "The file object is null." whenever ajax="true" and when set to false, works. I could not find a solution for this in the above referred thread.
Please advise.Also please let me know if you want any further information.

From PrimeFaces user guide:
Simple File Upload
Simple file upload mode works in legacy mode with a file input whose value should be an UploadedFile instance. Ajax uploads are not supported in simple upload.

Related

RichFaces fileUpload unable to invoke listener randomly

I am facing a problem using richfaces. I have a .jsp page where I'm using rich:fileUpload in it. When I upload the excel file, it should fill the datatable with corresponding values. On the localhost it works perfectly. Whenever I try it on the website, it works 90-95% of the times. I've been trying all day many solutions to try finding out the source of this bug but it's hopeless.
Can anybody help me please?
<h:form>
<table>
<tr>
<td>
<rich:fileUpload fileUploadListener="#{uploadToolBB.fileUploadListener}" id="uploadFile" ajaxSingle="true" allowFlash="false"
immediateUpload="false" listHeight="57px" listWidth="485px" maxFilesQuantity="1" acceptedTypes="xlsx"
noDuplicate="true" doneLabel="The file has been successfully uploaded" validatorMessage="An error occured while uploading the file">
<a4j:support event="onuploadcomplete" reRender="exceptionPanel,dataLst,uploadFile,fileName" oncomplete="Richfaces.hideModalPanel('importPanel');"/>
<a4j:support event="onclear" reRender="uploadFile" />
<f:facet name="label">
<h:outputText value="{_KB}KB from {KB}KB uploaded --- {mm}:{ss}" />
</f:facet>
</rich:fileUpload>
</td>
</tr>
</table>
</h:form>
When we click on upload the datatable should be filled with values, however it's not..no error is shown in the logs, all I could get is that it didn't invoke the fileUploadListener method in the bean.
public void fileUploadListener(UploadEvent event)
{
try {
UploadItem item = event.getUploadItem();
includedFabsHM.clear();
selecedUploadHist.setFileName(item.getFileName());
FctUploadedFileVO uploadedFile = new FctUploadedFileVO();
uploadedFile.setFile(item.getData());
selecedUploadHist.setUploadedFile(uploadedFile);
uploadToStagingTable(item.getData());
if(selecedUploadHist.getUploadHistoryId()!=0)
{
newFileUploaded = true;
}
}
catch (Exception e)
{
FacesUtil.handleFPException(FacesContext.getCurrentInstance(), e);
}
}

Notifying user download has finished.

Hi i have a command button.
I am using jsf 1.12 and tomahwak. I also am using jquery on client side.
<h:commandButton type="submit" value="Download Receipt"
onclick="refresh();"
id="downloadDocument"
actionListener="#{transactionPage.downloadReceipt}"
immediate="true"
/>
My jsf backing bean function
public void downloadReciept(final ActionEvent event) {
try{
DocManager docManager = new DocManager();
docManager.printDocs();
}catch (Exception e) {
log.error("Fail to download document!", e);
}
}
print docs would just create a file and stream it by setting the content-type, response, etc.
File sourceFile = createDoc();
Url url = sourceFile.toURI().toURL();
streamDoc(url);
I want to be able to display a message when downloading is starting and message when it finished
Hi thanks found my solution.
I change to commandLink than
set the cookie in backend and use jquery's file download

Upload an image to a Path set in web.xml using primefaces

I have consulted most of the posts here on stackoverflow on uploading images in primefaces. With this help, I have been able to upload an image to a destination path statically specified in code as shown in this post. save image file in specific directory jsf primefaces project. This works fine.
However, I wish to upload an Image to a desitnation path specified in web.xml. This is because I want the path to be configurable even after the application is deployed. When I use ServletContext#getRealpath(), the return path is with in the myProject folder, but I want the destination path to be completely external to the project since I have found it as the best way. e.g E:/myUploads
This is my web.xml
<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>51200</param-value>
</init-param>
<init-param>
<param-name>uploadDirectory</param-name>
<param-value>E:/myUploads</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
This is my bean.
public void handleFileUpload(FileUploadEvent event){
//get uploaded file from the event
UploadedFile uploadedFile = (UploadedFile) event.getFile();
//create an InputStream from the uploaded file
InputStream inputStr = null;
try
{
inputStr = uploadedFile.getInputstream();
} catch (IOException e) {
//log error
}
ServletContext servletContext = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
String uploadPath = servletContext.getRealPath("");
File destFile = new File(uploadPath);
//use org.apache.commons.io.FileUtils to copy the File
try {
FileUtils.copyInputStreamToFile(inputStr, destFile);
} catch (IOException e) {
//log error
}
FacesMessage msg = new FacesMessage(event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
My desire is to save the Uploaded Image in E:/myUploads without having to say:
String destPath = "E:\\myUploads\\" + uploadedFile.getFileName();
I will be glad if you also show me how to display the uploaded images using
<p:graphicImage
The uploadDirectory initialization parameter represents the temporary file storage location for the case the uploaded file is larger than the configured threshold size. The configured directory is not intented as a permanent file storage location. It will be auto-cleaned at moments beyond your control.
Get rid of it altogether and create an independent context parameter instead.
<context-param>
<param-name>uploadDirectory</param-name>
<param-value>E:/myUploads</param-value>
</context-param>
Then you can use
String directory = externalContext.getInitParameter("uploadDirectory");
String filename = FilenameUtils.getName(uploadedFile.getFileName());
File file = new File(directory, filename);
// ...
You should indeed never never use getRealPath(). You've by the way another potential problem when another user happens to upload a file with coincidentally the same filename. You can use File#createTempFile() to autogenerate unique filenames with a fixed prefix/suffix. See also How to save uploaded file in JSF.
BalusC Answer has helped me a great deal.. Thanks again BalusC. If any one is interested in the final code, here it is...
Am using tools Netbeans 7.4, Primefaces 4.0, GlassFish 3.1.2
This is my upload Form.
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}" mode="advanced" dragDropSupport="false"
update="messages" sizeLimit="100000" fileLimit="3" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />
<p:messages id="messages" showDetail="true"/>
</h:form>
I have the Apache Commons libraries in my lib
commons-io-2.4.jar (http://commons.apache.org/io)
commons-fileupload-1.3.jar (http://commons.apache.org/fileupload)
I have this in my web.xml
<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>51200</param-value>
</init-param>
</filter>
<context-param>
<param-name>uploadDirectory</param-name>
<param-value>E:/myUploads</param-value>
</context-param>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
This is my FileUploadController
#ManagedBean(name = "fileUploadController")
#ViewScoped
public class FileUploadController {
public void handleFileUpload(FileUploadEvent event) {
//get uploaded file from the event
UploadedFile uploadedFile = (UploadedFile) event.getFile();
//create an InputStream from the uploaded file
InputStream inputStr = null;
try {
inputStr = uploadedFile.getInputstream();
} catch (IOException e) {
//log error
}
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
String directory = externalContext.getInitParameter("uploadDirectory");
String filename = FilenameUtils.getName(uploadedFile.getFileName());
File destFile = new File(directory, filename);
//use org.apache.commons.io.FileUtils to copy the File
try {
FileUtils.copyInputStreamToFile(inputStr, destFile);
} catch (IOException e) {
//log error
}
FacesMessage msg = new FacesMessage(event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
This works well. All the best.

Permission denied in jnlp trying call showDocument with a pdf file

I need some help with this showDocument in my jnlp aplication.
I trying to show a pdf file in another tab from browser, but the java plugin denied.
My JNLP file has a
<security>
<all-permissions/>
</security>
and my code is:
AccessController.doPrivileged(new PrivilegedAction()
{
#Override
public Object run()
{
try
{
applet.getAppletContext().showDocument(new URL("file:///C:/Contrato.PDF"), "_blank");
}
catch(Exception e)
{
e.printStackTrace();
showException("Erro ao exibir arquivo:" + e.getMessage());
}
return null;
}
});
but I receive the exception
java.lang.SecurityException: showDocument url permission denied
If I try to do showDocument(google.com, _blank) that works...but when I try to show any file, it does not work.
The showDocument(URL) method of AppletContext was never intended for launching files off the local file-system (even when specified as a file protocol URL).
There are at least two alternatives:
The JNLP snippet indicates this is a trusted app., so for a 1.6+ app., Desktop.browse(URI) can be invoked.
The BasicService of the JNLP API offers the showDocument(URL) method.

Why can't I access managed bean methods from a JSF2 page?

In a <rich:popupPanel /> I have a <rich:fileUpload /> which has a fileUploadListener defined as #{assemblyMB.listener}. This listener method is defined on the managed bean as:
public void listener(FileUploadEvent event) throws Exception {
System.out.println("listener");
}
on the JSF page I have:
<rich:fileUpload id="popupFileUpload"
fileUploadListener="#{assemblyMB.listener}"
onuploadcomplete="#{rich:component('popup')}.hide(); return false;"
</rich:fileUpload>
On the managed bean, I have declared the annotation #ManagedBean(name = "assemblyMB").
I intend to access the method on the managed bean when the file is uploaded, but I'm failing to do so. I don't understand why is that happening.
Can anybody throw me a light here? Thanks in advance,
gtludwig
Assuming RichFaces 4.0, all you need to ensure is that the parent <h:form> is set to encode the request body as multipart/form-data.
<h:form enctype="multipart/form-data">
This way the file should be uploaded properly and the listener method should be invoked when the upload has been arrived in the server side.