import javax.faces.component.UIInput; //导入方法依赖的package包/类
public void decode(FacesContext context, UIComponent comp)
{
UIInput component = (UIInput) comp;
if (!component.isRendered()) return;
ExternalContext external = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) external.getRequest();
String clientId = component.getClientId(context);
String directory = (String) RendererUtil.getAttribute(context, component, "directory");
// mark that this component has had decode() called during request
// processing
request.setAttribute(clientId + ATTR_REQUEST_DECODED, "true");
// check for user errors and developer errors
boolean atDecodeTime = true;
String errorMessage = checkForErrors(context, component, clientId, atDecodeTime);
if (errorMessage != null)
{
addFacesMessage(context, clientId, errorMessage);
return;
}
// get the file item
FileItem item = getFileItem(context, component);
if (item.getName() == null || item.getName().length() == 0)
{
if (component.isRequired())
{
addFacesMessage(context, clientId, "Please specify a file.");
component.setValid(false);
}
return;
}
if (directory == null || directory.length() == 0)
{
// just passing on the FileItem as the value of the component, without persisting it.
component.setSubmittedValue(item);
}
else
{
// persisting to a permenent file in a directory.
// pass on the server-side filename as the value of the component.
File dir = new File(directory);
String filename = item.getName();
filename = filename.replace('\\','/'); // replaces Windows path seperator character "\" with "/"
filename = filename.substring(filename.lastIndexOf("/")+1);
File persistentFile = new File(dir, filename);
try
{
item.write(persistentFile);
component.setSubmittedValue(persistentFile.getPath());
}
catch (Exception ex)
{
throw new FacesException(ex);
}
}
}