巴巴运动网学习笔记(46-50)

实现文件上传模块
1.完成文件上传模块的实体bean和业务bean()

View Code
 1 package cnblogs.xiaoqiu.bean.upload;
 2 
 3 import java.io.Serializable;
 4 import java.util.Date;
 5 
 6 import javax.persistence.Column;
 7 import javax.persistence.Entity;
 8 import javax.persistence.GeneratedValue;
 9 import javax.persistence.Id;
10 import javax.persistence.Temporal;
11 import javax.persistence.TemporalType;
12 @Entity
13 public class UploadFile implements Serializable{
14     private static final long serialVersionUID = 3595994055420990951L;
15     private int id;
16     //上传文件的存放路径
17     private String filePath;
18     //文件的上传时间
19     private Date uploadTime = new Date();
20     @Id @GeneratedValue
21     public int getId() {
22         return id;
23     }
24     public void setId(int id) {
25         this.id = id;
26     }
27     @Column(nullable=false,length=80)
28     public String getFilePath() {
29         return filePath;
30     }
31     public void setFilePath(String filePath) {
32         this.filePath = filePath;
33     }
34     @Temporal(TemporalType.TIMESTAMP)
35     public Date getUploadTime() {
36         return uploadTime;
37     }
38     public void setUploadTime(Date uploadTime) {
39         this.uploadTime = uploadTime;
40     }
41     @Override
42     public int hashCode() {
43         final int prime = 31;
44         int result = 1;
45         result = prime * result + id;
46         return result;
47     }
48     @Override
49     public boolean equals(Object obj) {
50         if (this == obj)
51             return true;
52         if (obj == null)
53             return false;
54         if (getClass() != obj.getClass())
55             return false;
56         UploadFile other = (UploadFile) obj;
57         if (id != other.id)
58             return false;
59         return true;
60     }
61 }

2.完成文件上传模块的action和jsp和formbean

a.新建UploadManagerAction,实现文件上传功能

View Code
 1 package cnblogs.xiaoqiu.web.action.upload;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 import java.util.UUID;
 8 
 9 import javax.annotation.Resource;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 import org.apache.struts.action.ActionForm;
14 import org.apache.struts.action.ActionForward;
15 import org.apache.struts.action.ActionMapping;
16 import org.apache.struts.actions.DispatchAction;
17 import org.springframework.stereotype.Controller;
18 import cnblogs.xiaoqiu.bean.upload.UploadFile;
19 import cnblogs.xiaoqiu.service.upload.UploadService;
20 import cnblogs.xiaoqiu.web.action.formbean.UploadForm;
21 @Controller("/control/upload/manager")
22 public class UploadManagerAction extends DispatchAction{
23     @Resource(name="uploadServiceImpl")
24     private UploadService uploadService;
25     /**
26      * 提供上传界面
27      * @param mapping
28      * @param form
29      * @param request
30      * @param response
31      * @return
32      * @throws Exception
33      */
34     public ActionForward uploadUI(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)
35     throws Exception {
36         return mapping.findForward("upload");
37     }
38     
39     /**
40      * 实现上传功能
41      * @param mapping
42      * @param form
43      * @param request
44      * @param response
45      * @return
46      * @throws Exception
47      */
48     public ActionForward upload(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)
49     throws Exception {
50         UploadForm uploadForm = (UploadForm)form;
51         UploadFile uploadFile = new UploadFile();
52         String message="文件上传成功";
53         if(uploadForm.getUploadFile()!=null&&uploadForm.getUploadFile().getFileSize()>0){
54             if(uploadForm.isFileTypeValidate(uploadForm.getUploadFile())){
55                 StringBuffer fileDir = new StringBuffer("/file/upload/");
56                 SimpleDateFormat dateFormat = new SimpleDateFormat("yy/MM/dd/HH/");
57                 fileDir.append(dateFormat.format(new Date()));
58                 String imageRealDir = request.getSession().getServletContext().getRealPath(fileDir.toString());
59                 File dir = new File(imageRealDir);
60                 if(!dir.exists())    dir.mkdirs();
61                 StringBuffer imageName = new StringBuffer(UUID.randomUUID().toString());
62                 String fileExt = uploadForm.getUploadFile().getFileName().substring(uploadForm.getUploadFile().getFileName().lastIndexOf('.'));
63                 imageName.append(fileExt);
64                 FileOutputStream outputStream = new FileOutputStream(new File(imageRealDir,imageName.toString())); 
65                 outputStream.write(uploadForm.getUploadFile().getFileData());
66                 outputStream.close();
67                 uploadFile.setFilePath(fileDir.append(imageName).toString());
68                 uploadService.save(uploadFile);
69             }else{
70                 message = "文件类型不合法";
71             }
72         }else {
73             message = "文件上传失败";
74         }
75         request.setAttribute("message", message);
76         return mapping.findForward("uploadFinish");
77     }
78     
79 }

b.新建upload.jsp,添加对文件类型的客户端验证

View Code
 1 <%@ page contentType="text/html;charset=UTF-8" %>
 2 <%@ include file="/WEB-INF/page/share/taglib.jsp" %>
 3 <html>
 4 <head>
 5 <title>添加品牌</title>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <link rel="stylesheet" href="/css/vip.css" type="text/css">
 8 <SCRIPT language=JavaScript src="/js/FoshanRen.js"></SCRIPT>
 9 <script language="JavaScript">
10 function checkfm(form){
11     var fileName = trim(form.uploadFile.value);
12     if(fileName!=""){
13         var extName = fileName.substring(fileName.lastIndexOf('.')+1,fileName.split('').length);
14         var validateType = ["bmp","png","gif","jpg","txt","pdf","doc","xls","ppt"];
15         for(var i=0;i<validateType.length;i++){
16             if(extName==validateType[i])
17                 return true;
18         }
19         alert("文件格式不合法");
20         return false;
21     }else{
22         alert("文件不能为空");
23         return false;
24     }    
25     return true;
26 }
27 </script>
28 </head>
29 <body bgcolor="#FFFFFF" text="#000000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
30 <html:form action="/control/upload/manager" method="post"  enctype="multipart/form-data" onsubmit="return checkfm(this)">
31 <input type="hidden" name="method" value="upload">
32 <br>
33   <table width="90%" border="0" cellspacing="2" cellpadding="3" align="center">
34     <tr bgcolor="6f8ac4"><td colspan="2"  > <font color="#FFFFFF">文件上传:</font></td>
35     </tr>
36     <tr bgcolor="f5f5f5"> 
37       <td width="22%" > <div align="right">文件:</div></td>
38       <td width="78%"> <input type="file" name="uploadFile"/>
39         </td>
40     </tr>
41     <tr bgcolor="f5f5f5"> 
42       <td colspan="2"> <div align="center"> 
43           <input type="submit" name="SYS_SET" value=" 确 定 " class="frm_btn">
44         </div></td>
45     </tr>
46   </table>
47 </html:form>
48 <br>
49 </body>
50 </html>

c.formbean

View Code
 1 package cnblogs.xiaoqiu.web.action.formbean;
 2 
 3 import org.apache.struts.upload.FormFile;
 4 
 5 public class UploadForm extends BaseForm {
 6     private static final long serialVersionUID = 1724297881513682925L;
 7     
 8     private FormFile uploadFile;
 9     
10     public FormFile getUploadFile() {
11         return uploadFile;
12     }
13     
14     public void setUploadFile(FormFile uploadFile) {
15         this.uploadFile = uploadFile;
16     }
17     
18 }

3.完善文件类型验证的服务器端代码(txt,pdf,doc,xls,ppt)
4.使用配置文件来管理合法文件类型

View Code
 1 private static Properties pro = new Properties();
 2     static{
 3         try {
 4             pro.load(BaseForm.class.getClassLoader().getResourceAsStream("validateType.properties"));
 5         } catch (IOException e) {
 6             e.printStackTrace();
 7         }
 8     }
 9 /**
10      * 验证文件格式是否合法
11      * @param image
12      * @return
13      */
14     public boolean isFileTypeValidate(FormFile file){
15         if(file!=null&&file.getFileSize()>0){
16             String ext = file.getFileName().substring(file.getFileName().lastIndexOf('.')+1);
17             List<String> allowType = new ArrayList<String>();
18             for(Object key : pro.keySet()){
19                 String value = (String)pro.get(key);
20                 String[] valueArr = value.split(",");
21                 for(int i=0;i<valueArr.length;i++){
22                     allowType.add(valueArr[i]);
23                 }
24             }
25             return allowType.contains(file.getContentType())&&pro.keySet().contains(ext);
26         }
27         return false;
28     }

5.修改文件上传成功之后的消息页面(文件上传成功之后采用跳转的方式跳转到其他页面)

posted @ 2012-04-10 17:10  xiao秋  阅读(519)  评论(0编辑  收藏  举报