关于文件上传的例子

  本文使用FileUpload组件实现文件上传,前台页面包括有普通文本和文件上传同时进行提交,后台利用了一个servlet进行处理,处理后,将状态返回到页面的一个Iframe里面.功能比较简单,只是实现了一个上传,在异常处理等方面考虑的可能不周全,希望大家指正.

FileUploadServlet.java代码:

java 代码
  1. package tbg.upload;   
  2.   
  3. import java.io.File;   
  4. import java.io.IOException;   
  5. import java.io.PrintWriter;   
  6. import java.util.ArrayList;   
  7. import java.util.List;   
  8.   
  9. import javax.servlet.ServletException;   
  10. import javax.servlet.http.HttpServlet;   
  11. import javax.servlet.http.HttpServletRequest;   
  12. import javax.servlet.http.HttpServletResponse;   
  13.   
  14. import org.apache.commons.fileupload.FileItem;   
  15. import org.apache.commons.fileupload.FileUploadException;   
  16. import org.apache.commons.fileupload.disk.DiskFileItem;   
  17. import org.apache.commons.fileupload.disk.DiskFileItemFactory;   
  18. import org.apache.commons.fileupload.servlet.ServletFileUpload;   
  19.   
  20. public class FileUploadServlet extends HttpServlet {   
  21.   
  22.     /**  
  23.      * 保存版本信息  
  24.      */  
  25.     private static final long serialVersionUID = 1L;   
  26.        
  27.     // 默认文件上传保存路径   
  28.     public static final String UPLOAD_DIR = "/upload";   
  29.     // 默认字符集   
  30.     private static final String DEFAULT_ENCODING = "GBK";   
  31.     // 内存数据大小限制   
  32.     private int sizeThreshold = 256 * 1024;   
  33.     // request地最大值   
  34.     private long sizeMax = 256 * 1024 * 1024;   
  35.     // 单个上传文件大小限制   
  36.     private long singleSizeMax = 100 * 256 * 1024;    
  37.     // 文件临时存放路径   
  38.     private String tempDirectory = null;   
  39.     // 存放上传文件名的List   
  40.     ArrayList fileUploadList = new ArrayList();   
  41.     // 文件上传状态   
  42.     private String status = "";   
  43.        
  44.     /**  
  45.      * Constructor of the object.  
  46.      */  
  47.     public FileUploadServlet() {   
  48.         super();   
  49.     }   
  50.   
  51.     /**  
  52.      * Destruction of the servlet. 
     
  53.      */  
  54.     public void destroy() {   
  55.         super.destroy(); // Just puts "destroy" string in log   
  56.         // Put your code here   
  57.     }   
  58.   
  59.     /**  
  60.      * The doGet method of the servlet. 
     
  61.      *  
  62.      * This method is called when a form has its tag value method equals to get.  
  63.      *   
  64.      * @param request the request send by the client to the server  
  65.      * @param response the response send by the server to the client  
  66.      * @throws ServletException if an error occurred  
  67.      * @throws IOException if an error occurred  
  68.      */  
  69.     public void doGet(HttpServletRequest request, HttpServletResponse response)   
  70.             throws ServletException, IOException {   
  71.   
  72.         doPost(request, response);   
  73.     }   
  74.   
  75.     /**  
  76.      * The doPost method of the servlet. 
     
  77.      *  
  78.      * This method is called when a form has its tag value method equals to post.  
  79.      *   
  80.      * @param request the request send by the client to the server  
  81.      * @param response the response send by the server to the client  
  82.      * @throws ServletException if an error occurred  
  83.      * @throws IOException if an error occurred  
  84.      */  
  85.     public void doPost(HttpServletRequest request, HttpServletResponse response)   
  86.             throws ServletException, IOException {   
  87.   
  88.         response.setContentType("text/html; charset=gb2312");   
  89.         PrintWriter out = null;   
  90.            
  91.         boolean isMultiPart = ServletFileUpload.isMultipartContent(request);   
  92.         if (isMultiPart) {   
  93.             processFileUpload(request, response);   
  94.         }   
  95.         out = response.getWriter();    
  96.         out.write(status);   
  97.         out.print("
    "
    );   
  98.         for (int i = 0; i < fileUploadList.size(); i++) {   
  99.             out.write((String) fileUploadList.get(i));   
  100.             out.print("
    "
    );   
  101.         }   
  102.         out.flush();   
  103.         out.close();   
  104.         fileUploadList.clear();   
  105.     }   
  106.   
  107.     /**  
  108.      * Initialization of the servlet. 
     
  109.      *  
  110.      * @throws ServletException if an error occure  
  111.      */  
  112.     public void init() throws ServletException {   
  113.         // Put your code here   
  114.     }   
  115.        
  116.     /**  
  117.      * 处理文件上传  
  118.      */  
  119.     private void processFileUpload (HttpServletRequest request, HttpServletResponse response)    
  120.                 throws ServletException, IOException {   
  121.         DiskFileItemFactory factory = new DiskFileItemFactory();   
  122.         // 设置内容缓冲区,超过后写入临时文件   
  123.         factory.setSizeThreshold(sizeThreshold);   
  124.         // 得到文件临时存放地位置   
  125.         if (tempDirectory == null) {   
  126.             tempDirectory = request.getSession().getServletContext().getRealPath("/upload/temp");   
  127.         }   
  128.         // 设置文件临时存放位置   
  129.         factory.setRepository(new File(tempDirectory));   
  130.         // 设置单个文件地最大上传值   
  131.         ServletFileUpload upload = new ServletFileUpload(factory);   
  132.         // 设置字符集   
  133.         upload.setHeaderEncoding(request.getCharacterEncoding());   
  134.         // 设置单个文件上传地最大值   
  135.         upload.setFileSizeMax(singleSizeMax);   
  136.         // 设置request地最大值   
  137.         upload.setSizeMax(sizeMax);   
  138.             
  139.         try {   
  140.             List items = upload.parseRequest(request);   
  141.             // 处理文件上传   
  142.             for (int i = 0; i < items.size(); i++) {   
  143.                 FileItem item = (FileItem) items.get(i);   
  144.                 // 保存文件   
  145.                 if (!item.isFormField() && item.getName().length() > 0) {   
  146.                     // 取得文件地名字   
  147.                     String fileName = takeFileName(item.getName());   
  148.                     // 取得文件上传路径   
  149.                     String fileRealPath =    
  150.                         request.getSession().getServletContext().getRealPath(UPLOAD_DIR) + File.separator + fileName;   
  151.                     File uploadFile = new File(fileRealPath);   
  152.                     item.write(uploadFile);   
  153.                     // 更新文件上传列表   
  154.                     fileUploadList.add(fileName);   
  155.                     status = "上传成功";   
  156.                    
  157.                     Thread.sleep(500);   
  158.                 } else {   
  159.                     String encoding = "";   
  160.                     String formFieldName = "";   
  161.                     // 设置字符集   
  162.                     if (item instanceof DiskFileItem) {   
  163.                         encoding = ((DiskFileItem) item).getCharSet();   
  164.                     } else {   
  165.                         encoding = request.getCharacterEncoding();   
  166.                     }   
  167.                     // 取得控件对应的值   
  168.                     if (encoding != null) {   
  169.                         formFieldName = item.getString(encoding);   
  170.                     } else {   
  171.                         formFieldName = item.getString(DEFAULT_ENCODING);   
  172.                     }   
  173.                     fileUploadList.add(formFieldName);   
  174.                    
  175.                 }   
  176.             }   
  177.         } catch (FileUploadException e) {   
  178.             uploadExceptionHandle(request, "文件上传错误:" + e.getMessage());   
  179.         } catch (Exception e) {   
  180.             uploadExceptionHandle(request, "保存文件时错误:" + e.getMessage());   
  181.         }   
  182.            
  183.     }   
  184.        
  185.     /**  
  186.      * 从文件路径中取出文件名  
  187.      */  
  188.     private String takeFileName (String filePath) {   
  189.         int pos = filePath.lastIndexOf(File.separator);   
  190.         if (pos > 0) {   
  191.             return filePath.substring(pos + 1);   
  192.         } else {   
  193.             return filePath;   
  194.         }   
  195.     }   
  196.        
  197.     /**  
  198.      * 上传失败处理  
  199.      */  
  200.     private void uploadExceptionHandle (HttpServletRequest request, String errMes) {   
  201.         deleteUploadFile(request);   
  202.         status = errMes;   
  203.     }   
  204.        
  205.     /**  
  206.      * 删除已上传文件  
  207.      */  
  208.     private void deleteUploadFile (HttpServletRequest request) {   
  209.         for (int i = 0; i < fileUploadList.size(); i++) {   
  210.             String fileRealPath =    
  211.                 request.getSession().getServletContext().getRealPath(UPLOAD_DIR)    
  212.                 + File.separator + fileUploadList.get(i);   
  213.             File uploadFile = new File(fileRealPath);   
  214.             uploadFile.delete();   
  215.         }   
  216.         fileUploadList.clear();   
  217.         status = "文件已经被删除";   
  218.     }   
  219.   
  220. }   

页面:uploadIndex.jsp

页面抓图

 

提交后:

IFrame现实的是主题 内容和文件名...

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值