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
Related
I have an MP3 audio file outside of the application context, in C:/platform/musig.mp3.
I'm using the below servlet to serve it.
public class AudioServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
stream = response.getOutputStream();
File mp3 = new File("C:/platform/music.mp3");
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentLength((int) mp3.length());
FileInputStream input = new FileInputStream(mp3);
buf = new BufferedInputStream(input);
int readBytes = 0;
while ((readBytes = buf.read()) != -1) {
stream.write(readBytes);
}
} finally {
if (stream != null) {
stream.close();
}
if (buf != null) {
buf.close();
}
}
}
}
<servlet>
<servlet-name>audioServlet</servlet-name>
<servlet-class>servlet.AudioServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>audioServlet</servlet-name>
<url-pattern>/audio/*</url-pattern>
</servlet-mapping>
I'm referencing it in <p:media> as below:
<p:media id="media"
value="/audio"
player="quicktime"
width="200"
height="40">
<f:param name="autoPlay" value="false" />
</p:media>
The problem is that I am unable to run the sound. If I put the audio file within the application context (in /resources for example), it works. But out of context, it does not work at all.
The below exception appears in the console when the servlet is invoked:
ClientAbortException: java.net.SocketException: Software Caused connection abort: socket write error
Does anyone have any idea what might be happening? Or is there another way to perform MP3 with the "media" component PrimeFaces I do not know?
I managed to solve :) ... I used to address the response of 0x5a4d and Balusc, with the code 0x5a4d was released a scope error, I'm using in my application the 'Conversation Scope' and launched an exception ... the Balusc commented that the answer was incomplete and could be released this mistake, and that's what happened ...
Then I create a separate Bean only to process the request to MP3 with the 'Default Scope', and it worked ... my class was so.
.
#Named
public class AudioBean {
private StreamedContent media;
public AudioBean() throws FileNotFoundException {
InputStream stream = new FileInputStream("C:\\plataforma\\music.mp3");
media = new DefaultStreamedContent(stream, "audio/mpeg");
}
public StreamedContent getMedia() { return media; }
}
and *.xhtml
<p:media value="#{audioBean.media}"
width="250"
height="225"
player="quicktime"/>
Thank you guys for the help!
like this code skeleton:
*.xhtml
<p:media value="#{mediaBean.media}" width="250" height="225" player="quicktime"/>
#Bean
public class MediaBean {
private StreamedContent media;
public MediaController() {
InputStream stream = new FileInputStream("C://filename.mp3");
media = new DefaultStreamedContent(stream, "audio/mpeg");
}
public StreamedContent getMedia() { return media; }
}
In this example i remove other code for simplify:
#ManagedBean(name = "mediaBean")
#RequestScoped
public class MediaBean{
public StreamedContent getMedia() throws FileNotFoundException{
return new DefaultStreamedContent(new FileInputStream("PATH_TO_MEDIA_FILE"),"audio/mpeg");
}
}
}
Choose the scope you based on your requirement, in my case it was request.
As explanation About
java.net.SocketException: Broken pipe
and not close stream help this and this posts.
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" .
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)}" .....
This question already has answers here:
How to provide a file download from a JSF backing bean?
(5 answers)
Closed 5 years ago.
I want to download a .txt/.log file saved in hard disk in JSF, am not getting any error but the issue is am not able to download the file, need some help..
note : am trying to zip the file first and then download.
I have tried :
response.setContentType("text/html");
response.setContentType("text/plain");
Code in page.xhtml:
<h:form>
<a4j:outputPanel id="downloadPanel">
<table><tr>
<td>
<h:commandButton id="dldFiles" title="Download File" image="/images/download.png"
style="width:20px; height:20px;"/>
</td>
<td>
<h:outputText value="Download log file" style="font-size: 11px; color:#56ADF8; font-weight: bold; cursor:pointer;"/>
</td>
</tr></table>
<a4j:support event="onclick" action="#{sqlLoaderAction.downloadFile}" reRender="uploadForm"></a4j:support>
</a4j:outputPanel>
</rich:panel>
</h:form>
In Actin Bean Methods:
public String downloadFile(){
System.out.println("--inside exportGoogleFeed--");
FacesContext fc = FacesContext.getCurrentInstance();
try{
User user = getUserBean();
Object sp = getServiceProxy(user);
HttpServletResponse response = ((HttpServletResponse)fc.getExternalContext().getResponse());
fc.responseComplete();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=downloadname.zip");
OutputStream respOs = response.getOutputStream();
String dldFileName = "SQLLDR_28.txt";
PrintWriter pw1 = new PrintWriter(new FileWriter(dldFileName , false));
BufferedReader readbuffer = new BufferedReader(new FileReader("D:/Sqlldr_Container/downloadFile.txt"));
String strRead;
while((strRead=readbuffer.readLine())!=null){
pw1.println(strRead);
}
pw1.close();
File fil = new File(dldFileName);
ZipUploadStatusFile(dldFileName, respOs);
boolean bool = fil.delete();
System.out.println("-------Temp file Created deleted - "+bool+" ------------");
readbuffer.close();
}
catch (UnAuthenticatedException e) {
e.printStackTrace();
} /*catch (UnAuthorizedAccessException e) {
e.printStackTrace();
}*/ catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void ZipUploadStatusFile(String fileName, OutputStream respOs){
try{
ZipOutputStream out = new ZipOutputStream(respOs);
byte[] data = new byte[1000];
BufferedInputStream in = new BufferedInputStream
(new FileInputStream(fileName));
int count;
out.putNextEntry(new ZipEntry(fileName));
while((count = in.read(data,0,1000)) != -1){
out.write(data, 0, count);
}
in.close();
out.flush();
out.close();
System.out.println("Your file is zipped");
}catch(Exception e){
e.printStackTrace();
}
}
After executing the above method am getting below screen:
Thank you.....
You can't download files by ajax. JavaScript has due to security reasons no facilities to force a Save As dialogue. The best it could do in your particular case is to display the response inline.
Get rid of the <a4j:support> and make it a fullworthy synchronous request by putting the action method straight in the <h:commandButton>.
This is the code that will fulfill the needs of downloading text file in to client system.
public String downloadFileText() {
File file = new File(GlobalPath);
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename=file.txt");
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
return null;
}
I dont think that the code will run fine because the code is in JSF MAnaged beans and it is running at server side, so file will be downloaded at the system where application server is running, now what you need to do is to check , use two pcs,
In one pc deploy the web and try to download file from other pc, then check the behaviour of code, if the file could be downloaded in client pc then thats fine other wise you need to find alternatives
i am using the ace:fileEntry component to upload files
and after successful upload i get the message that:
'File Entry' uploaded successfully 'filename'.
and i want to override this message and display other message (some kind of a summary for parsing that uploaded file), any ideas how ?
here's my code:
<h:form>
<ace:fileEntry id="fileEntryComp"
label="File Entry"
relativePath="uploaded"
fileEntryListener="#{mybean.uploadFile}"/>
<h:commandButton value="Upload Excel File" />
<h:message for="fileEntryComp" />
</h:form>
The fileEntry.getResults().getFiles() gives you an ArrayList of FileInfo objects.
If you upload only one file, you can get the FileInfo the following way:
FileInfo fileInfo = fileEntry.getResults().getFiles().get(0);
You should call the updateStatus method of the FileInfo the following way to override the default message:
fileInfo.updateStatus(new FileEntryStatus() {
#Override
public boolean isSuccess() {
return true;
}
#Override
public FacesMessage getFacesMessage(FacesContext facesContext,
UIComponent fileEntry, FileEntryResults.FileInfo fi) {
return new FacesMessage(FacesMessage.SEVERITY_INFO,
"My success message: " + fi.getFileName(),
"My success message: " + fi.getFileName());
}
}, true, true);
You have to create your own message and send it. It will overwrite the default message. Its a strange behavior but it will work.
public void uploadFile(FileEntryEvent e) {
FileEntry fe = (FileEntry)e.getComponent();
FacesContext ctx = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage();
msg.setServity(FacesMessage.SERVITY_INFO);
msg.setSummary("mysummary");
msg.setDetail("mydetail");
ctx.addMessage(fe.getClientId(),msg);
}
You can check the showcase: http://comp-suite.icefaces.org/comp-suite/showcase.jsf?grp=aceMenu&exp=fileEntry
You can override icefaces messages.
Default message bundle (just to know which message to ovverride) can be found in icefaces source package:
icefaces3/ace/component/src/org/icefaces/ace/resources/messages.properties
where:
org.icefaces.ace.component.fileEntry.SUCCESS = ''{0}'' has successfully uploaded ''{1}''
org.icefaces.ace.component.fileEntry.SUCCESS_detail = ''{0}'' has successfully uploaded ''{1}''
and these are lines I put in my application.properties file:
org.icefaces.ace.component.fileEntry.SUCCESS = File ''{1}'' caricato correttamente
org.icefaces.ace.component.fileEntry.SUCCESS_detail = File ''{1}'' caricato correttamente
be sure to have application.properties defined in faces-config.xml and visible by you application:
<application>
<message-bundle>application</message-bundle>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
</application>
This can be done with all Icefaces default messages ...