2007-12-04

File upload with ajax (form base async)

使用ajax傳送檔案回去server, 找了一下ajax 相關的東西, 發現只能用form 的上把資料傳回去.
這一次的研究希望能夠做到 google mail 那樣的單檔上傳的功能.所以, 預計要達到的目的是, html page 不用重新由server 端產生, 並且可以回傳上傳檔案的相關資料.

client code
















server code

FileUploadParser parser = new FileUploadParser("big5", -1);

Model model = parser.parse(request);
Model fields = (Model)model.get("FormValues");
Model files = (Model)model.get("Files");
Object[] filenames = files.getKeys();

ArrayModel f = new ArrayModel();
for(int i=0;i {
SimpleModel m = new SimpleModel();
m.set("FileName",filenames[i]);

FileItem item = (FileItem)files.get(filenames[i]);
m.set("FileSize",String.valueOf(item.getSize()));

File file = new File(");
try
{
item.write(file);
item.delete();
}
catch (Exception e)
{
e.printStackTrace();
}
f.add(m);
}
model.set("Files",f);
response.setContentType("text/html");
response.getWriter().write(model.toJSON() );