Natural

 

servlet伪异步上传文件

在web开发中,上传文件是常遇到的问题。
本文在页面上用iframe来“异步”上传,并返回上传结果;来实现常见的文件异步上传。

常用的手法,通过一个隐藏的iframe来“异步”
<form action="servletUploadFile" target="_fileUpload" method="post" enctype="multipart/form-data" name="form1">   
    
<input type="file" name="file" class="text"/>   
    
<input type="submit" name="submit" value="上传"/>   
</form>
    
<div id="_uploadresult">这里用来显示上传结果</div>
    
<iframe name="_fileUpload" style="display:none"></iframe>

通过 commons-fileupload.jar包实现上传功能的servlet

  1 package com.company.servlet;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.io.PrintWriter;
  6 import java.util.Iterator;
  7 import java.util.List;
  8 
  9 import javax.servlet.ServletConfig;
 10 import javax.servlet.ServletContext;
 11 import javax.servlet.ServletException;
 12 import javax.servlet.http.HttpServlet;
 13 import javax.servlet.http.HttpServletRequest;
 14 import javax.servlet.http.HttpServletResponse;
 15 
 16 import org.apache.commons.fileupload.DiskFileUpload;
 17 import org.apache.commons.fileupload.FileItem;
 18 import org.apache.commons.fileupload.FileUploadException;
 19 import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
 20 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 21 import org.apache.commons.fileupload.servlet.ServletFileUpload;
 22 
 23 public class UploadFile extends HttpServlet {
 24 
 25     private String uploadPath; // 上传文件的目录  
 26     private String uploadtempPath; // 临时文件目录  
 27     
 28     private static final long serialVersionUID = 1068590804829697704L;  
 29     private ServletContext sc;//获取设备上下文对象  
 30     private String savePath;//保存的路径web.xml中所配置的路径
 31     private String savePathTemp;//上传时临时保存的路径 web.xml中所配置的路径
 32     
 33     /*
 34     public void doPost(HttpServletRequest request, HttpServletResponse response)
 35     throws ServletException, IOException 
 36     {
 37         response.setContentType("text/html;charset=utf-8");
 38         final long MAX_SIZE = 1024 * 1024 * 1024;// 设置上传文件最大为 1G
 39         final String str_MAX_SIZE = "1G"; //用于输出
 40 
 41         final String[] allowedExt = new String[] { "flv" }; // 允许上传的文件格式的列表  
 42 
 43         StringBuffer result = null;    // 准备写到页面的结果信息
 44         List fileItems = null;
 45         PrintWriter out = response.getWriter();
 46 
 47 
 48         // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload  
 49         DiskFileItemFactory dfif = new DiskFileItemFactory(); 
 50 
 51         dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘  
 52         dfif.setRepository(new File(uploadtempPath));// 设置存放临时文件的目录,保存在web根目录下的web.xml配置文件中savePathTemp目录下 
 53 
 54         // 用以上工厂实例化上传组件  
 55         ServletFileUpload sfu = new ServletFileUpload(dfif);
 56 
 57 
 58         sfu.setSizeMax(MAX_SIZE);   // 设置最大文件尺寸
 59 
 60         try
 61         {  
 62             fileItems = sfu.parseRequest(request);  // 得到所有的文件:
 63         } catch (FileUploadException e) // 处理文件尺寸过大异常  
 64         {
 65             if (e instanceof SizeLimitExceededException) 
 66             {  
 67                 result = new StringBuffer("文件尺寸超过规定大小:" + str_MAX_SIZE );
 68                 myPrintOut(out,result.toString()); 
 69                 return;  
 70             }  
 71             e.printStackTrace();  
 72         }  
 73 
 74         // 没有文件上传  
 75         if (fileItems == null || fileItems.size() == 0) {  
 76             result = new StringBuffer("请选择上传文件");
 77             myPrintOut(out,result.toString());  
 78             return;  
 79         }
 80 
 81         Iterator iter = fileItems.iterator();   
 82         
 83         // 依次处理每一个文件:   
 84         while(iter.hasNext()) 
 85         {
 86             FileItem fileItem = null;
 87             String path = null;
 88             long size = 0; 
 89             
 90             fileItem = (FileItem)iter.next();   
 91          
 92             if(fileItem == null || fileItem.isFormField())// 当前是一个表单项
 93                 continue;
 94     
 95             path = fileItem.getName();   // 获得文件名 或得到文件的完整路径 
 96          
 97             size = fileItem.getSize();  // 得到文件的大小
 98     
 99             if ("".equals(path) || size == 0) {  
100                 result = new StringBuffer("请选择上传文件");
101                 myPrintOut(out,result.toString()); 
102                 return;  
103             }  
104 
105             // 得到去除路径的文件名  
106             String t_name = path.substring(path.lastIndexOf("\\") + 1);  
107             // 得到文件的扩展名(无扩展名时将得到全名)  
108             String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);  
109          
110             // 拒绝接受规定文件格式之外的文件类型  
111             int allowFlag = 0;  
112             int allowedExtCount = allowedExt.length;  
113             for (; allowFlag < allowedExtCount; allowFlag++) 
114             {  
115                 if (allowedExt[allowFlag].equals(t_ext))  
116                     break;  
117             }  
118             if (allowFlag == allowedExtCount) 
119             {
120                 result = new StringBuffer("请上传以下类型的文件&nbsp;&nbsp;");
121                 
122                 for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)  
123                     result.append(allowedExt[allowFlag]+"&nbsp;");
124                 
125                 myPrintOut(out,result.toString());
126                 return;  
127             }  
128     
129             long now = System.currentTimeMillis();  // 根据系统时间生成上传后保存的文件名
130     
131             String prefix = String.valueOf(now);  
132             // 保存的最终文件完整路径,保存在web根目录下的web.xml配置文件中savePath目录下  
133             String u_name = uploadPath  +"\\" + prefix + "." + t_ext;  
134     
135             // 写入文件   
136             try {
137                 fileItem.write(new File(u_name));
138             } catch (Exception e) 
139             {
140                 e.printStackTrace();
141             }
142     
143             result = new StringBuffer("文件上传成功. 已保存为:");
144             result.append(u_name);
145 
146             myPrintOut(out,result.toString());
147         }
148     }
149     */
150     
151     public void doPost(HttpServletRequest request, HttpServletResponse response)
152             throws ServletException, IOException 
153     {
154         response.setContentType("text/html;charset=utf-8");
155         final long MAX_SIZE = 1024 * 1024 * 1024;// 设置上传文件最大为 1G
156         final String str_MAX_SIZE = "1G"//用于输出
157         
158         final String[] allowedExt = new String[] { "flv" }; // 允许上传的文件格式的列表  
159         
160         StringBuffer result = null;    // 准备写到页面的结果信息
161         List fileItems = null;
162         PrintWriter out = response.getWriter();
163         
164         DiskFileUpload fu = new DiskFileUpload();   
165         
166         fu.setSizeMax(MAX_SIZE);   // 设置最大文件尺寸
167         fu.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
168         fu.setRepositoryPath(uploadtempPath);   // 设置临时目录:
169         
170         try
171         {  
172             fileItems = fu.parseRequest(request);  // 得到所有的文件:
173         } catch (FileUploadException e) // 处理文件尺寸过大异常  
174         {
175             if (e instanceof SizeLimitExceededException) 
176             {  
177                 result = new StringBuffer("文件尺寸超过规定大小:" + str_MAX_SIZE );
178                 myPrintOut(out,result.toString()); 
179                 return;  
180             }  
181             e.printStackTrace();  
182         }  
183         
184         // 没有文件上传  
185         if (fileItems == null || fileItems.size() == 0) {  
186                 result = new StringBuffer("请选择上传文件");
187                 myPrintOut(out,result.toString());  
188              return;  
189         }
190         
191         Iterator iter = fileItems.iterator();   
192 
193         // 依次处理每一个文件:   
194         while(iter.hasNext()) 
195         {
196             FileItem fileItem = null;
197             String path = null;
198             long size = 0
199 
200             fileItem = (FileItem)iter.next();   
201                  
202             if(fileItem == null || fileItem.isFormField())// 当前是一个表单项
203                 continue;
204             
205             path = fileItem.getName();   // 获得文件名 或得到文件的完整路径 
206                  
207             size = fileItem.getSize();  // 得到文件的大小
208             
209             if ("".equals(path) || size == 0) {  
210                     result = new StringBuffer("请选择上传文件");
211                     myPrintOut(out,result.toString()); 
212                  return;  
213             }  
214        
215             // 得到去除路径的文件名  
216             String t_name = path.substring(path.lastIndexOf("\\"+ 1);  
217             // 得到文件的扩展名(无扩展名时将得到全名)  
218             String t_ext = t_name.substring(t_name.lastIndexOf("."+ 1);  
219                  
220             // 拒绝接受规定文件格式之外的文件类型  
221             int allowFlag = 0;  
222             int allowedExtCount = allowedExt.length;  
223             for (; allowFlag < allowedExtCount; allowFlag++
224             {  
225                 if (allowedExt[allowFlag].equals(t_ext))  
226                     break;  
227             }  
228             if (allowFlag == allowedExtCount) 
229             {
230                 result = new StringBuffer("请上传以下类型的文件&nbsp;&nbsp;");
231                      
232                 for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)  
233                     result.append(allowedExt[allowFlag]+"&nbsp;");
234                     
235                     myPrintOut(out,result.toString());
236                     return;  
237             }  
238             
239             long now = System.currentTimeMillis();  // 根据系统时间生成上传后保存的文件名
240             
241             String prefix = String.valueOf(now);  
242             // 保存的最终文件完整路径,保存在web根目录下的web.xml配置文件中savePath目录下  
243             String u_name = uploadPath  +"\\" + prefix + "." + t_ext;  
244             
245             // 写入文件   
246             try {
247                 fileItem.write(new File(u_name));
248             } catch (Exception e) 
249             {
250                 e.printStackTrace();
251             }
252             
253             result = new StringBuffer("文件上传成功. 已保存为:");
254             result.append(prefix + "." + t_ext);
255 
256             myPrintOut(out,result.toString());
257          }
258     }
259     
260     public void myPrintOut(PrintWriter out, String str)
261     {
262         out.println("<script>window.parent.document.getElementById(\"_uploadresult\").innerHTML='"+str+"'</script>");
263     }
264 
265     public void init(ServletConfig config) throws ServletException {
266         //获取配置文件保存的变量值  
267         savePath = config.getInitParameter("savePath");  
268         savePathTemp  = config.getInitParameter("savePathTemp"); 
269         //获取Servlet上下文对象  
270         sc = config.getServletContext(); 
271         
272         uploadPath = sc.getRealPath("/")+savePath;//上传文件的路径
273         uploadtempPath = sc.getRealPath("/")+savePathTemp;//上传文件临时文件的路径
274         
275         //      文件夹不存在就自动创建:   
276         if(!new File(uploadPath).isDirectory())   
277             new File(uploadPath).mkdirs();   
278         if(!new File(uploadtempPath).isDirectory())   
279             new File(uploadtempPath).mkdirs(); 
280     }
281 
282 }
283 

在web.xml中配置一下
其中参数
savePath是用来设置上传文件的路径
savePathTemp是用来设置上传文件的临时路径(web应用根目录下)
<servlet>
    
<servlet-name>servletUploadFile</servlet-name>
    
<servlet-class>com.company.servlet.UploadFile</servlet-class>
    
<init-param>
      
<param-name>savePath</param-name>
      
<param-value>fileUpload</param-value>
    
</init-param>
    
<init-param>
      
<param-name>savePathTemp</param-name>
      
<param-value>fileUploadTemp</param-value>
    
</init-param>
  
</servlet>
  
<servlet-mapping>
    
<servlet-name>servletUploadFile</servlet-name>
    
<url-pattern>/servletUploadFile</url-pattern>
  
</servlet-mapping>


posted on 2010-03-24 22:50 此号已被删 阅读(488) 评论(0)  编辑  收藏 所属分类: J2EE


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(8)

随笔分类(83)

随笔档案(78)

文章档案(2)

相册

收藏夹(7)

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜