01: package simpleorm.simplewebapp.eg.simple;
02:
03: import simpleorm.simplewebapp.core.*;
04: import simpleorm.simplewebapp.scalarFields.WFieldString;
05: import org.apache.commons.fileupload.FileItem;
06:
07: import java.io.*;
08: import java.util.List;
09: import java.util.Iterator;
10:
11: /**
12: * Uploads a file and then downloads it immediately back to the user.
13: */
14: public class WUploadPage extends WPage {
15: public final WUploadPagelet pagelet = new WUploadPagelet(this );
16:
17: public static class WUploadPagelet extends WPagelet {
18:
19: final WButton upload = addNewButton("Upload");
20:
21: WFieldGroup identity = addGroup(this , new WFieldGroup("upload"));
22: final WFieldString field = addField(identity, new WFieldString(
23: "myfield"));
24: final WFieldString file = addField(identity, new WFieldString(
25: "file", WField.FILE));
26:
27: public WUploadPagelet(WPage wpage) {
28: super (wpage, "crud");
29: getPageStructure().setMultipart(true);
30: }
31:
32: public @Override
33: void onInitialize() throws Exception {
34: List<FileItem> items = getPage().getPageContext()
35: .parseUploadFileItems();
36: if (items == null)
37: return; // not a file, just an ordindary get/post.
38:
39: Iterator iter = items.iterator();
40: while (iter.hasNext()) {
41: FileItem item = (FileItem) iter.next();
42: // Non-file items already removed by parseUploadFileItems
43: String fieldName = item.getFieldName();
44: String fileName = item.getName();
45: String contentType = item.getContentType();
46: boolean isInMemory = item.isInMemory();
47: long sizeInBytes = item.getSize();
48:
49: debug("Upload File FieldName: " + fieldName
50: + " filelName: " + fileName + " contentType: "
51: + contentType + " inMem: " + isInMemory
52: + " size: " + sizeInBytes);
53: // Process a file upload in memory
54: //byte[] data = item.get();
55:
56: // File uploadedFile = new File(...);
57: // item.write(uploadedFile);
58:
59: InputStream uploadedStream = item.getInputStream();
60:
61: OutputStream outputStream = getPage().getPageContext()
62: .openDownloadStream(fileName);
63: try {
64: byte[] buf = new byte[4 * 1024]; // 4K buffer
65: int bytesRead;
66: while ((bytesRead = uploadedStream.read(buf)) != -1) {
67: outputStream.write(buf, 0, bytesRead);
68: //System.err.write(buf, 0, bytesRead);
69: }
70: } finally {
71: uploadedStream.close();
72: }
73: }
74: }
75: }
76: }
|