JAVAWEB学习制作自己的小说管理网站-day03

主要实现了文件上传的uploadServlet,以及uploadDownload.jsp

上传文件功能实现的代码:

1.用apache的commons-fileupload组件实现

  
  
  
  
  1. @Override 
  2.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  3.             throws ServletException, IOException {  
  4.         //判断类型  
  5.         boolean isMultipart = ServletFileUpload.isMultipartContent(req);  
  6.           
  7.         if(isMultipart){  
  8.             FileItemFactory factory = new DiskFileItemFactory();  
  9.             ServletFileUpload upload = new ServletFileUpload(factory);  
  10.               
  11.             try {  
  12.                 List items = upload.parseRequest(req);  
  13.                 Iterator iter = items.iterator();  
  14.                 while(iter.hasNext()){  
  15.                     FileItem item = (FileItem)iter.next();  
  16.                     if(item.isFormField()){  
  17.                         processFormField(item);  
  18.                         req.getRequestDispatcher("/main.jsp").forward(req, resp);  
  19.                     }else{  
  20.                         if(processUploadFile(item,req)){  
  21.                             req.getSession(true).setAttribute("fileUpload","success fileUpload");  
  22.                         }else{  
  23.                             req.getSession(true).setAttribute("fileUpload","failure fileUpload");     
  24.                         }  
  25.                     }  
  26.                 }  
  27.                 if(req.getSession(true).getAttribute("fileUpload").equals("success fileUpload")){                     
  28.                     resp.sendRedirect(req.getContextPath()+"/uploadDownload.jsp");  
  29.                 }else{  
  30.                     resp.sendRedirect(req.getContextPath()+"/uploadDownload.jsp");  
  31.                 }  
  32.             } catch (FileUploadException e) {  
  33.                 e.printStackTrace();  
  34.             }  
  35.         }  
  36.     }  
  37.       
  38.     public boolean processUploadFile(FileItem item, HttpServletRequest req){  
  39.         if(!item.isFormField()){  
  40.             String fileName = item.getName();  
  41.             fileName = fileName.substring(fileName.lastIndexOf("\\")+1);  
  42.             System.out.println("fileName:"+fileName);  
  43.             if(fileName.equals("")||fileName.equals(null)){  
  44.                 System.out.println("match");  
  45.                 return false;  
  46.             }  
  47.             String root = getServletContext().getRealPath("/");  
  48.             File path = new File(root + "/WEB-INF/uploads/" + req.getSession(true).getAttribute("username"));  
  49.             if(!path.exists()){  
  50.                 path.mkdirs();  
  51.             }  
  52.               
  53.             File uploadFile = new File(path+"/"+fileName);  
  54.             System.out.println(uploadFile);  
  55.               
  56.             try {  
  57.                 item.write(uploadFile);  
  58.             } catch (Exception e) {  
  59.                 e.printStackTrace();  
  60.             }  
  61.               
  62.             FileOutputStream uploadZipFileOutputStream = null;  
  63.             try {  
  64.                 uploadZipFileOutputStream = new FileOutputStream(path+"/"+fileName+".zip");  
  65.             } catch (FileNotFoundException e1) {  
  66.                 e1.printStackTrace();  
  67.             }  
  68.             ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(uploadZipFileOutputStream));  
  69.               
  70.             byte[] data = new byte[1000];  
  71.             try {  
  72.                 BufferedInputStream in = new BufferedInputStream(new FileInputStream(uploadFile));  
  73.                 int count;  
  74.                 try {  
  75.                     out.putNextEntry(new ZipEntry(fileName+".zip"));  
  76.                     while((count = in.read(data,0,1000)) != -1){  
  77.                         out.write(data,0,count);  
  78.                     }  
  79.                     in.close();  
  80.                     out.flush();  
  81.                     out.close();  
  82.                     System.out.println("Your file is zipped!");  
  83.                 } catch (IOException e) {  
  84.                     e.printStackTrace();  
  85.                 }  
  86.             } catch (FileNotFoundException e1) {  
  87.                 e1.printStackTrace();  
  88.             }  
  89.                   
  90.             uploadFile.delete();      
  91.         }  
  92.         return true;  
  93.     }  
  94.       
  95.     public void processFormField(FileItem item){  
  96.         if(item.isFormField()){  
  97.             String name = item.getFieldName();  
  98.             String value = item.getString();  
  99.             if(name.equals("storyName")){  
  100.                   
  101.             }else if(name.equals("writer")){  
  102.                   
  103.             }else if(name.equals("description")){  
  104.                   
  105.             }  
  106.         }  
  107.     } 


 

上传文件实现的页面:

 1上传的页面包括 label+file+input,可以上传多个文件,点击按钮,可以动态添加一栏上传文件的标记

  
  
  
  
  1. <%@ page language="java" contentType="text/html; charset=utf-8" 
  2.     pageEncoding="utf-8"%> 
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
  4. <html> 
  5. <head> 
  6.  
  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
  8. <title>upload and download file page</title> 
  9.  
  10.     <script type="text/javascript"> 
  11.         var i = 2;  
  12.         function addFileUploadTag()  
  13.         {  
  14.             var br = document.createElement("br");  
  15.             document.getElementById("file"+(i-1)).appendChild(br);  
  16.             var dynDiv = document.createElement("div");  
  17.             dynDiv.id = "file"+i;  
  18.             var label = document.createElement("label");  
  19.             label.innerHTML = "Story"+(i++)+":";  
  20.             var file = document.createElement("input");  
  21.             file.type = "file";  
  22.             file.name = "file"+(i-1);  
  23.             file.size = "5";  
  24.             var formCom = document.getElementById("form01");  
  25.             dynDiv.style.height = "20px";          
  26.             dynDiv.style.width = "300px";  
  27.             dynDiv.style.display = "inline";  
  28.               
  29.             var labelStoryName = document.createElement("label");  
  30.             labelStoryName.innerHTML = "storyName:";  
  31.             var storyName = document.createElement("input");  
  32.             storyName.type="text";  
  33.             storyName.name = "storyName";  
  34.  
  35.             var labelWriter = document.createElement("label");  
  36.             labelWriter.innerHTML = "writer:";  
  37.             var writer = document.createElement("input");  
  38.             writer.type="text";  
  39.             writer.name="writer";  
  40.               
  41.             var labelDescription = document.createElement("label");  
  42.             labelDescription.innerHTML = "description:";  
  43.             var description = document.createElement("textarea");  
  44.             description.name = "description";  
  45.  
  46.             var labelCover = document.createElement("cover");  
  47.             labelCover.innerHTML = "cover:";  
  48.             var cover = document.createElement("input");  
  49.             cover.type = "file";  
  50.             cover.name = "cover" + (i-1);  
  51.             cover.size = "5";   
  52.               
  53.               
  54.             dynDiv.appendChild(label);  
  55.             dynDiv.appendChild(file);  
  56.             dynDiv.appendChild(labelStoryName);  
  57.             dynDiv.appendChild(storyName);  
  58.             dynDiv.appendChild(labelWriter);  
  59.             dynDiv.appendChild(writer);  
  60.             dynDiv.appendChild(labelDescription);  
  61.             dynDiv.appendChild(description);  
  62.             document.getElementById("file"+(i-2)).appendChild(dynDiv);  
  63.         }  
  64.  
  65.     </script> 
  66.  
  67. </head> 
  68. <body> 
  69.     <h1>upload list:</h1> 
  70.     <h2 style="color:red;">Attention:all upload files will be stored in zip format in server.</h2> 
  71.     <hr> 
  72.     <form id="form01" method="post" action="upload" ENCTYPE="multipart/form-data"> 
  73.         <div id="file1"> 
  74.             Story1:<input id="file111" type="file" name="story1" size="5"/> 
  75.             storyName:<input type="text" name="storyName"/> 
  76.             writer:<input type="text" name="writer"/> 
  77.             description:<textarea rows="" cols="" name="textArea"></textarea> 
  78.         </div> 
  79.           
  80.         <div id = "button"> 
  81.             <input type="button" value="addAnotherFile" onclick="addFileUploadTag();"/> 
  82.             <input type="submit" value="clickToUploadAll"/> 
  83.         </div> 
  84.       
  85.     </form> 
  86.       
  87.     <h1>fileUploadResult:${sessionScope.fileUpload}</h1> 
  88.       
  89.     <hr> 
  90.       
  91.     <h1>download list</h1> 
  92.           
  93.       
  94. </body> 
  95. </html> 

需要实现的功能:把图片预览,导入上来,把上传的文件保存到数据库中,路径保存到表中,实现注册功能。

本文出自 “AhahaGe” 博客,谢绝转载!

你可能感兴趣的:(上传文件)