So guys , I've decided to do a college's "homework" using JSF 2.2 and PrimeFaces 5.0 and theoretically I'm at the end , but I have great difficulty uploading files and , after trying by the whole day , I decided to post. The problem is that the file does not go where it should go, but the method is performed and shows no errors and exceptions.
page.xhtml
<p:fileUpload id="msg"
fileUploadListener="#{processoCtrl.handleFileUpload}"
allowTypes="/(\.|\/)(doc|docx|pdf)$/" mode="advanced"
sizeLimit="10485760"
invalidFileMessage="Formato de arquivo inválido"/>
<p:messages id="messages" showDetail="true" autoUpdate="true" closable="true"/>
ManagedBean
public void handleFileUpload(FileUploadEvent event) {
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
// I already tryed //WEB-INF// , \\WEB-INF\\ e \WEB-INF\ (who knows...)
File result = new File(extContext.getRealPath("/WEB-INF/" + event.getFile().getFileName()));
System.out.println("/WEB-INF/" + event.getFile().getFileName());
try {
FileOutputStream fileOutputStream = new FileOutputStream(result);
byte[] buffer = new byte[6124];
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();
FacesMessage msg = new FacesMessage("File Description", "file name: " +
event.getFile().getFileName() + " file size: " +
event.getFile().getSize() / 1024 + "Kb content type: " +
event.getFile().getContentType() + "The file was uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "erro.");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
Part of 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>
/var/temp
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
PS : This was the last attempt by today after numerous! And This one seemed a lil "better" .
Related
Occurs at the time of loading the page, in addition to the parcer does not find the channel room or can not read some characters.
<p:socket onMessage="handleMessage" channel="/{room}" autoConnect="false" widgetVar='subscriber' />
Caused by:
java.lang.IllegalArgumentException: [/context/primepush/{room}] is not a valid URL fragment. Consider encoding relevant portions of the URL with [class org.ocpsoft.urlbuilder.util.Encoder]
my web.xml
<servlet>
<servlet-name>Push Servlet</servlet-name>
<servlet-class>org.primefaces.push.PushServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>Push Servlet</servlet-name>
<url-pattern>/primepush/*</url-pattern>
</servlet-mapping>
in my bean
public void login(BLogin log) {
RequestContext requestContext = RequestContext.getCurrentInstance();
username=log.getLogNombres()+" "+log.getLogApellidos();
if(users.contains(username)) {
//loggedIn = false;
//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Username taken", "Try with another username."));
//requestContext.update("growl");
// requestContext.execute("PF('subscriber').connect('/" + username + "')");
loggedIn = true;
}
else{
users.add(username);
requestContext.execute("PF('subscriber').connect('/" + username + "')");
loggedIn = true;
}
}
my xhtml
<f:metadata>
<f:event type="preRenderView" listener="#{chatView.login(bLoginController.getbLogin())}" />
</f:metadata>
<p:growl id="growl" showDetail="true"/>
<p:socket onMessage="handleMessage" channel="/{room}" autoConnect="false" widgetVar='subscriber' />
<script type="text/javascript">
function handleMessage(message) {
var chatContent = $(PrimeFaces.escapeClientId('form:public')),
text = (message.user) ? message.user + ':' + message.text : message.text;
chatContent.append(text + '<br />');
//keep scroll
chatContent.scrollTop(chatContent.height());
if (message.updateList) {
updateList();
}
}
</script>
I try
<p:socket onMessage="handleMessage" channel="/%7Broom%7D"
and other error
16:16:21,998 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (default task-16) Error Rendering View[/pages/home.xhtml]: java.lang.IllegalStateException: No parameter [room] was set in the pattern [/context/primepush/{room}]. Call address.set("room", value); or remove the parameter from the pattern.
The error occurs because Rewrite/PrettyFaces fails to parse the corresponding URL. That is probably because your are using a VERY old version of Rewrite/PrettyFaces from 2013. Please update to 3.4.1.Final. There has been some bugfixes regarding URL parsing in the latest releases and I'm confident that updating will fix your problem.
See:
https://github.com/ocpsoft/rewrite/issues/224
The solution is to only write / room without the relatives and the connections were created correctly
<p:socket onMessage="handleMessage" channel="/room" autoConnect="false" widgetVar='subscriber' />
I'm trying insert a download in my webApplication.
First of all the page which contains the form where there is the is on
citizen/createparty.xhtml
And the folder where i'd like to upload the file is
partysymbols/ ..
Then i show to you the XHTML code:
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{partyCreationBean.file}" mode="simple" />
<p:commandButton value="Submit" ajax="false" actionListener="#{partyCreationBean.upload}" />
Then the partyCreationBean
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
....
public void handleFileUpload() {
File target = new File(FacesContext.getCurrentInstance().getApplication().get);
System.out.println("handle file upload: " + file.getFileName());
InputStream inputStream;
try {
inputStream = file.getInputstream();
OutputStream out = new FileOutputStream(file.getFileName()
);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
System.out.println("done");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void upload() {
if(file != null) {
FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
handleFileUpload();
}
}
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>
<init-param>
<param-name>uploadDirectory</param-name>
<param-value>partysymbols</param-value>
</init-param>
</filter>
The problem is that I reach the
System.out.println("done")
but I have no idea of where the file is uploaded.
then also, if i understood well the "uploadDirectory" parameter in the web.xml is not to set the directory where the file is setted.
I don't really understand how to do this stuff, also because it's first time that i work for a webapplication, and i use glassfish, and i have no idea about how the file system should work... I mean... i don't know where in reality are the pages and all the stuff... i just know where they are inside eclipse :/
Thankyou a lot in advance
Samuele
I guess there is an error in your handleFileUpload() method:
The line
OutputStream out = new FileOutputStream(file.getFileName());
should probably be:
OutputStream out = new FileOutputStream(target.getAbsolutePath() + file.getFileName());
This should also be the path where the file finally is stored, you can print it with:
System.out.println("Path: " + target.getAbsolutePath() + file.getFileName());
The line where the target var is initialized in your code seems to miss something but I guess it retrieves the uploadDirectory param from the web.xml.
You may have to set up an absolute path for the uploadDirectory param like "c:\\tmp\\partysymbols" (Windows) or "/home/user/partysymbols" (Unix) in your web.xml.
See also:
Where does p:fileUpload save my file?
j2ee primefaces fileupload file saving destination
Good day to all!
I've been making a simple web Application using Netbeans, JSF and Primefaces that can upload .csv, .jpeg/.jpg and .pdf files. I made 2 folders which was stored in drive C: (uploaded folder and tmp folder).
I assigned the "uploaded" folder to where the uploaded files are stored and the "tmp" for the .tmp of the uploaded files. I've been through many question threads and video tutorial which I followed correctly.
I also downloaded the commons fileupload and commons io and added it to the library. It is working fine, it displays that it is uploading and even saw the .tmp file on the folder i assigned it to.
But I cannot see the uploaded files on my "uploaded" folder.
So, my question is,
How can I upload these files into my "uploaded" folder.
Here are my codes:
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data" >
<p:fileUpload fileUploadListener="#{FileUploadControl.fileUploadControl}"
mode="advanced"
update="messages"
auto="true"
sizeLimit="10000000"
allowTypes="/(\.|\/)(gif|jpe?g|csv|pdf)$/"
/>
<!-- -->
<p:growl id="messages" showDetail="true"/>
</h:form>
</h:body>
</html>
FileUploadControl.java
package controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.model.UploadedFile;
#ManagedBean
#SessionScoped
public class FileUploadControl implements Serializable {
private String destination = "C:\\uploaded\\";
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public FileUploadControl() {
}
public void TransferFile(String fileName, InputStream in) {
try {
OutputStream out = new FileOutputStream(new File(destination + fileName));
int reader = 0;
byte[] bytes = new byte[(int) getFile().getSize()];
while ((reader = in.read(bytes)) != -1) {
out.write(bytes, 0, reader);
}
in.close();
out.flush();
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void upload() {
String extValidate;
if (getFile() != null) {
String ext = getFile().getFileName();
if (ext != null) {
extValidate = ext.substring(ext.indexOf(".")+1);
} else {
extValidate = "null";
if (extValidate.equals("pdf")) {
try {
TransferFile(getFile().getFileName(), getFile().getInputstream());
} catch (IOException ex) {
Logger.getLogger(FileUploadControl.class.getName()).log(Level.SEVERE, null, ex);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Wrong", "Error Uploading file..."));
}
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Succesful", getFile().getFileName() + "is uploaded."));
} else {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Wrong_ext", "only extension .pdf"));
}
}
} else {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Wrong", "Select File!"));
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!--File upload commons -->
<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>C:\tmp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<!--File upload commons -->
<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>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
Thank you for your response and help. looking forward to it!
The main reason it's failing as at now is that you haven't bound the value attribute to your backing bean variable, so getFile() will always return null and upload will do nothing.
You're still probably not going to get any results because it appears that you're trying to combine two different modes of operation of the <p:fileUpload/> component.
Simple mode
You don't define a fileUploadListener
You define a value attribute on the component and bind to the UploadedFile type attribute in your backing bean (which you have)
Advanced mode
You don't define a value attribute
You define a fileUploadListener which is bound to a method in your backing bean (which you also have)
I've put wro.xml in src/main/resources as there are some other resources and it's easier to access them in unit tests.
I need to extend some wro classes now to be able to read the model from another place, but can't get it working.
Necessary code
web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>WebResourceOptimizer</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>wroFilter</param-value>
</init-param>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>WebResourceOptimizer</filter-name>
<url-pattern>/resources/*</url-pattern>
</filter-mapping>
applicationContext.xml:
<bean id="wroFilter" class="ro.isdc.wro.http.ConfigurableWroFilter">
<property name="properties" ref="wroProperties" />
</bean>
<bean id="wroProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:wro.properties" />
</bean>
wro.properties:
managerFactoryClassName=com.example.web.wro.manager.factory.MyWroManagerFactory;
preProcessors=cssUrlRewriting,cssImport,semicolonAppender,lessCss
postProcessors=cssMin,jsMin
debug=true
MyWroManagerFactory:
public class MyWroManagerFactory extends CopyrightKeeperConfigurableWroManagerFactory {
private static final Logger LOG = LoggerFactory.getLogger(MyWroManagerFactory.class);
#Override
protected WroModelFactory newModelFactory() {
LOG.debug("Load wro.xml directly from classpath");
return new XmlModelFactory() {
#Override
protected InputStream getModelResourceAsStream() throws IOException {
final String resourceLocation = getDefaultModelFilename();
final InputStream stream = getClass().getResourceAsStream(resourceLocation);
if (stream == null) {
throw new IOException("Invalid resource requested: " + resourceLocation);
}
return stream;
}
};
}
}
CopyrightKeeperConfigurableWroManagerFactory:
public class CopyrightKeeperConfigurableWroManagerFactory extends ConfigurableWroManagerFactory {
private static final Logger LOG = LoggerFactory.getLogger(CopyrightKeeperConfigurableWroManagerFactory.class);
private static final String[] PROCESSORS = {
CssImportPreProcessor.ALIAS,
JawrCssMinifierProcessor.ALIAS,
CssMinProcessor.ALIAS,
JSMinProcessor.ALIAS
};
#Override
protected void contributePreProcessors(final Map<String, ResourcePreProcessor> map) {
for (String processor : PROCESSORS) {
if (map.containsKey(processor)) {
LOG.debug("Apply CopyrightKeeperProcessorDecorator on " + processor);
map.put(processor, CopyrightKeeperProcessorDecorator.decorate(map.get(processor)));
}
}
}
}
Why it can't find classes/wro.xml / How to use a custom location for wro.xml?
EDIT
Here's the full log output: http://pastebin.com/NeNy1NH4
The problem is that you are loading the model relative to the MyWroManagerFactory class:
final InputStream stream = getClass().getResourceAsStream(resourceLocation);
That means that it will look for the model in the folder where the class is located. Since your wro.xml is located in classes folder (which is a root for classpath), you should use the following:
ClassLoader.getSystemResourceAsStream(resourceLocation);
Alternatively you could use ClasspathUriLocator:
new ClasspathUriLocator().locate("classpath:" + resourceLocation)
EDITED:
Apparently this example discovered a problem which is described in the following issue:
Until the fix is ready, the following options are available:
Option 1
Option 2
I've done this part of the form
<td>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{uploadBean.handleFileUpload(event)}"
mode="advanced"
update="messages"
multiple="true"
sizeLimit="2000000"
allowTypes="/(\.|\/)(pdf|doc?x|xls?x)$/"/>
<p:growl id="messages" showDetail="true"/>
</h:form>
</td>
and this event handler in class:
public class UploadBean {
/** Creates a new instance of UploadBean */
public UploadBean() {
}
private static final int BUFFER_SIZE = 6124;
public void handleFileUpload(FileUploadEvent event) {
ExternalContext extContext = FacesContext.getCurrentInstance().
getExternalContext();
File result = new File(extContext.getRealPath
("//WEB-INF//upload") + "//" + event.getFile().getFileName());
try {
FileOutputStream fileOutputStream = new FileOutputStream(result);
byte[] buffer = new byte[BUFFER_SIZE];
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();
FacesMessage msg = new FacesMessage("Succesful",
event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (IOException e) {
FacesMessage error = new FacesMessage("The files were not uploaded!");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
}
Now the handling method I got it from a site. I am not sure why this is failing to upload. it looks okay to me. Maybe am missing something? so the control appears on my page and I can choose file, but then upload progress bar just proceeds fast...no growl notification shows and also no file uploaded of course.
Thanks,
From the docs (Assuming using Primefaces)
First thing to do is to configure the fileupload filter which parses the multipart request. FileUpload filter should map to Faces Servlet.
<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>
Hope you are not missing this setting.
Also not sure whats event in your code
<p:fileUpload fileUploadListener="#{uploadBean.handleFileUpload(event)}" .....