File Upload
FileUploadForm.java
package
org.apache.myfaces.examples.misc;
import
java.io.IOException;
import
org.apache.myfaces.custom.fileupload.UploadedFile;
import
javax.faces.context.FacesContext;
public class FileUploadForm
{
private UploadedFile
_upFile;
private String _name = "";
//
getters and setters
public String upload() throws IOException
{
FacesContext facesContext =
FacesContext.getCurrentInstance();
facesContext.getExternalContext().getApplicationMap().put("fileupload_bytes",
_upFile.getBytes());
facesContext.getExternalContext().getApplicationMap().put("fileupload_type",
_upFile.getContentType());
facesContext.getExternalContext().getApplicationMap().put("fileupload_name", _upFile.getName());
return "ok";
}
public boolean isUploaded()
{
FacesContext facesContext =
FacesContext.getCurrentInstance();
return
facesContext.getExternalContext().getApplicationMap().get("fileupload_bytes")!=null;
}
}
fileupload_showing.jsp
<%@ page import="java.io.File,
java.io.InputStream,
java.io.FileInputStream,
java.io.OutputStream"%><%@ page session="false"
%><%
String contentType =
(String)application.getAttribute("fileupload_type");
String fileName =
(String)application.getAttribute("fileupload_name");
String allowCache = request.getParameter("allowCache");
String openDirectly =
request.getParameter("openDirectly");
if(allowCache == null ||
allowCache.equalsIgnoreCase("false"))
{
response.setHeader("pragma", "no-cache");
response.setHeader("Cache-control", "no-cache,
no-store, must-revalidate");
response.setHeader("Expires", "01 Apr 1995
01:10:10 GMT");
}
if(contentType!=null)
{
response.setContentType(contentType);
}
if(fileName != null)
{
fileName =
fileName.substring(fileName.lastIndexOf('\\')+1);
fileName =
fileName.substring(fileName.lastIndexOf('/')+1);
StringBuffer contentDisposition = new StringBuffer();
if(openDirectly==null ||
openDirectly.equalsIgnoreCase("false"))
{
contentDisposition.append("attachment;");
}
contentDisposition.append("filename=\"");
contentDisposition.append(fileName);
contentDisposition.append("\"");
response.setHeader ("Content-Disposition",
contentDisposition.toString());
}
byte[] bytes = (byte[])application.getAttribute("fileupload_bytes");
if (bytes != null)
{
response.getOutputStream().write(bytes);
}
%>