JAVA 大作业——DAY 5

进度日记:9.2

18:27 终于完成上传图片的功能

servlet中获得当前工程路径

1 String path = getServletContext().getRealPath("/");

html中form

1 <form enctype="multipart/form-data" action="/Browser/UploadServlet" method="post" >
2 <input type="hidden" name="userID" id="userID" value="" />
3 <div><b>Choose the file To Upload:</b>
4 <input name="file" TYPE="file" /></div>
5 <div><input class="super-emphasize" type="submit" value="Save" /></div>
6 </form>

UploadServlet,获得图片和其他参数。

其中,因为form的enctype="multipart/form-data",所以userID无法用response.getParameter()方法获得!

 1        DiskFileItemFactory fac = new DiskFileItemFactory();
 2             ServletFileUpload upload = new ServletFileUpload(fac);
 3             upload.setHeaderEncoding("utf-8");
 4             List fileList = null;
 5             fileList = upload.parseRequest(request);
 6             userID = ((FileItem)fileList.get(0)).getString();   //获取userID参数
 7             if (userID == null) {
 8                 userID = "get no name";
 9             }
10             System.out.println(userID);
11                  
12             Iterator<FileItem> it = fileList.iterator();
13             String name = "";
14             while (it.hasNext()) {
15                 FileItem item = it.next();
16                 if (!item.isFormField()) {
17                     name = item.getName();
18                     if (name == "" || name == null) {
19                         throw new Exception();    
20                     }
21                     File file = new File(path + File.separatorChar + userID + name);
22                     if (file.exists()) {
23                         errorMessage = "该文件已经存在!请重命名后再上传。";
24                     }
25                     item.write(file);
26                     item.delete();  //释放输出流
27                 }
28             }
posted @ 2012-09-02 18:33  ReasonHan  阅读(166)  评论(0编辑  收藏  举报