Kamis, 30 Januari 2014

Uploading files with JSF



WARNING - OUTDATED CONTENT!


This article is targeted on JSF 1.2. For JSF 2.0/2.1 with Tomahawk, please checkout my answer on this Stackoverflow.com question. For JSF 2.0/2.1 on Servlet 3.0 with a custom component, please checkout this article. For JSF 2.2, just use its native file upload component in flavor of whose value can be tied to a javax.servlet.http.Part property.







Upload and store files


Downloading files is made relatively easy using a FileServlet, but uploading files is a bit harder. Entering/selecting the raw absolute file path in h:inputText and sending it to the server so that it can be used in a File object isn't going to work, as the server doesn't have access to the client's file system. That will work only if the server as well as the client runs on the same machine and that wouldn't occur in real life.



To browse and select a file for upload you basically need a HTML input type="file" field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form have to be set to "multipart/form-data". Unfortunately the Sun JSF Reference Implementation Mojarra doesn't provide a component out of the box which renders a input type="file" field. But the MyFaces Tomahawk component library, which can also be integrated in Sun JSF Reference Implementation Mojarra, provides us the t:inputFileUpload component.


Back to top


Integrating Tomahawk in Mojarra


Assuming that you already have a Mojarra environment, you just need to add at least the following JAR's to the classpath, e.g. /WEB-INF/lib. The version numbers doesn't matter that much, as long as you get the newest.



The Tomahawk JAR is the Tomahawk component library itself which under each contains the t:inputFileUpload component and the ExtensionsFilter. The commons-fileupload and commons-io JAR's are required for the file upload. They contains a multipart/form-data parser and several I/O utilities respectively. The commons-logging and commons-el JAR's are required by the core of the Tomahawk component library.


After adding the JAR's, open your web.xml and add the ExtensionsFilter to it. It should filter multipart/form-data requests and make use of the commons-fileupload to parse the request. To get uploading files work in JSF, it should at least be mapped on the servlet name of the FacesServlet, which may differ per environment. By default it is "Faces Servlet". Just check the servlet name in its definition.




Extensions Filter
org.apache.myfaces.webapp.filter.ExtensionsFilter


Extensions Filter
Faces Servlet


It is not required, but you can configure the ExtensionsFilter with one or more of the following useful init-param settings which you can put in the tag:







Set the size limit for uploaded files.
Format: 10 - 10 bytes
10k - 10 KB
10m - 10 MB
1g - 1 GB

uploadMaxFileSize
100m



Set the threshold size - files below this limit are stored
in memory, files above this limit are stored on disk.
Format: 10 - 10 bytes
10k - 10 KB
10m - 10 MB
1g - 1 GB

uploadThresholdSize
100k



Set the path where the intermediary files will be stored.

uploadRepositoryPath
/temp



Back to top


Basic use example


Here is a basic use example of a JSF file and the appropriate backing bean which demonstrates the working of the t:inputFileUpload.



<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t" %>

html>


lang="en">

</span>File upload test<span class="codetag">


id="uploadForm" enctype="multipart/form-data">
columns="3">
for="file" value="Select file" />
id="file" value="#{myBean.uploadedFile}" required="true" />
for="file" style="color: red;" />

/>
value="Submit" action="#{myBean.submit}" />
for="uploadForm" infoStyle="color: green;" errorStyle="color: red;" />



value="file/#{myBean.fileName}" rendered="#{myBean.fileName != null}">
Download back





Please note the enctype of the h:form. This is required to be able to POST binary data. Also note that the download link makes use of the FileServlet. Make sure that it points to the same directory as where the file is uploaded. You can configure it as an init-param.



Here is how the appropriate backing bean (request scoped) look like:



package mypackage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

public class MyBean {

// Init ---------------------------------------------------------------------------------------

private UploadedFile uploadedFile;
private String fileName;

// Actions ------------------------------------------------------------------------------------

public void submit() {

// Just to demonstrate what information you can get from the uploaded file.
System.out.println("File type: " + uploadedFile.getContentType());
System.out.println("File name: " + uploadedFile.getName());
System.out.println("File size: " + uploadedFile.getSize() + " bytes");

// Prepare filename prefix and suffix for an unique filename in upload folder.
String prefix = FilenameUtils.getBaseName(uploadedFile.getName());
String suffix = FilenameUtils.getExtension(uploadedFile.getName());

// Prepare file and outputstream.
File file = null;
OutputStream output = null;

try {
// Create file with unique name in upload folder and write to it.
file = File.createTempFile(prefix + "_", "." + suffix, new File("c:/upload"));
output = new FileOutputStream(file);
IOUtils.copy(uploadedFile.getInputStream(), output);
fileName = file.getName();

// Show succes message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_INFO, "File upload succeed!", null));
} catch (IOException e) {
// Cleanup.
if (file != null) file.delete();

// Show error message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));

// Always log stacktraces (with a real logger).
e.printStackTrace();
} finally {
IOUtils.closeQuietly(output);
}
}

// Getters ------------------------------------------------------------------------------------

public UploadedFile getUploadedFile() {
return uploadedFile;
}

public String getFileName() {
return fileName;
}

// Setters ------------------------------------------------------------------------------------

public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}

}


Note: make "c:/upload" at least configureable. Maybe as a property in a propertiesfile which could also be shared by the FileServlet.



Back to top


Copyright - There is no copyright on the code. You can copy, change and distribute it freely. Just mentioning this site should be fair.


(C) February 2008, BalusC



Source:http://balusc.blogspot.com/2008/02/uploading-files-with-jsf.html

Tidak ada komentar:

Posting Komentar