Examples
Provides a file upload form and displays the results of the upload.
To save the uploaded file to the WEB context path, rather than the default
java path, use the ServletContext.getRealPath() method to
obtain the web application's directory path.
<form jwcid="@Form" listener="ognl:listener.formSubmit">
<table bgcolor="#c0c0c0" cellpadding="4">
<tr>
<td colspan="2">File: <input jwcid="@Upload" file="ognl:file" type= "file"></input></td>
</tr>
<tr>
<td colspan="2"><input type= "submit"value="Upload"></input></td>
</tr>
<tr>
<td colspan="2"><hr></td>
</tr>
<tr>
<td>Filename:</td><td><span jwcid="@Insert" value="ognl:filename"/>/td>
</tr>
<tr>
<td>Client path:</td><td><span jwcid="@Insert" value="ognl:clientPath"/></td>
</tr>
<tr>
<td>Server Path:</td><td><span jwcid="@Insert" value="ognl:serverPath"/></td>
</tr>
<tr>
<td>File Truncated:</td><td><span jwcid="@Insert" value="ognl:fileTruncated"/></td>
</tr>
<tr>
<td>File Size:</td><td><span jwcid="@Insert" value="ognl:fileSize" format="ognl:@UploadPage@SIZE_FORMAT"/> bytes</td>
</tr>
</table>
</form>
public class UploadPage extends BasePage {
public static final Format SIZE_FORMAT = NumberFormat.getNumberInstance();
private IUploadFile file;
private File serverFile;
public IUploadFile getFile() { return file; }
public void setFile(IUploadFile value) {
file = value;
}
public String getFilename() {
if (file != null) {
return file.getFileName();
} else {
return "";
}
}
public String getClientPath() {
if (file != null) {
return file.getFilePath();
} else {
return "";
}
}
public String getServerPath() {
if (serverFile != null) {
return serverFile.getAbsolutePath();
} else {
return "";
}
}
public long getFileSize() {
if (serverFile != null) {
return serverFile.length();
} else {
return 0;
}
}
public boolean isFileTruncated() {
if (file != null) {
return file.isTruncated();
} else {
return false;
}
}
public void formSubmit(IRequestCycle cycle) {
InputStream fis = file.getStream();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(file.getFileName()));
byte[] buffer = new byte[1024];
while (true) {
int length = fis.read(buffer);
if (length < 0) {
break;
}
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
serverFile = new File(file.getFileName());
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (fis != null) {
try { fis.close(); } catch (IOException ioe) {}
}
if (fos != null) {
try { fos.close(); } catch (IOException ioe) {}
}
}
}
protected void initialize() {
file = null;
serverFile = null;
}
}
|