<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    小菜毛毛技術分享

    與大家共同成長

      BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
      164 Posts :: 141 Stories :: 94 Comments :: 0 Trackbacks
    版權聲明:原創作品,允許轉載,轉載時請務必以超鏈接形式標明文章 原始出處 、作者信息和本聲明。否則將追究法律責任。http://zhangjunhd.blog.51cto.com/113473/18331
    Apachecommons-fileupload.jar可方便的實現文件的上傳功能,本文通過實例來介紹如何使用commons-fileupload.jar
    @author:ZJ 07-2-22
        將Apachecommons-fileupload.jar放在應用程序的WEB-INF"lib即可使用。下面舉例介紹如何使用它的文件上傳功能。
    所使用的fileUpload版本為1.2,環境為Eclipse3.3+MyEclipse6.0FileUpload 是基于 Commons IO的,所以在進入項目前先確定Commons IOjar包(本文使用commons-io-1.3.2.jar)在WEB-INF"lib下。
    此文作示例工程可在文章最后的附件中下載。
    示例1
    最簡單的例子,通過ServletFileUpload靜態類來解析Request,工廠類FileItemFactory會對mulipart類的表單中的所有字段進行處理,不只是file字段。getName()得到文件名,getString()得到表單數據內容,isFormField()可判斷是否為普通的表單項。
    demo1.html
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
        <title>File upload</title>
    </head>
    <body>
           //必須是multipart的表單數據。
        <form name="myform" action="demo1.jsp" method="post"
           enctype="multipart/form-data">
           Your name:<br>
           <input type="text" name="name" size="15"><br>
           File:<br>
           <input type="file" name="myfile"><br>
           <br>
           <input type="submit" name="submit" value="Commit">
        </form>
    </body>
    </html>
     
    demo1.jsp
    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <%@ page import="org.apache.commons.fileupload.*"%>
    <%@ page import="org.apache.commons.fileupload.servlet.*"%>
    <%@ page import="org.apache.commons.fileupload.disk.*"%>
    <%@ page import="java.util.*"%>
     
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);//檢查輸入請求是否為multipart表單數據。
        if (isMultipart == true) {
           FileItemFactory factory = new DiskFileItemFactory();//為該請求創建一個DiskFileItemFactory對象通過它來解析請求。執行解析后,所有的表單項目都保存在一個List中。
           ServletFileUpload upload = new ServletFileUpload(factory);
           List<FileItem> items = upload.parseRequest(request);
           Iterator<FileItem> itr = items.iterator();
           while (itr.hasNext()) {
               FileItem item = (FileItem) itr.next();
               //檢查當前項目是普通表單項目還是上傳文件。
               if (item.isFormField()) {//如果是普通表單項目,顯示表單內容。
           String fieldName = item.getFieldName();
           if (fieldName.equals("name")) //對應demo1.htmltype="text" name="name"
               out.print("the field name is" + item.getString());//顯示表單內容。
           out.print("<br>");
               } else {//如果是上傳文件,顯示文件名。
           out.print("the upload file name is" + item.getName());
           out.print("<br>");
               }
           }
        } else {
           out.print("the enctype must be multipart/form-data");
        }
    %>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
        <title>File upload</title>
    </head>
    <body>
    </body>
    </html>
    結果:
    the field name isjeff
    the upload file name isD:"C語言考試樣題"作業題.rar
    示例2
    上傳兩個文件到指定的目錄。
    demo2.html
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
        <title>File upload</title>
    </head>
    <body>
        <form name="myform" action="demo2.jsp" method="post"
           enctype="multipart/form-data">
           File1:<br>
           <input type="file" name="myfile"><br>
           File2:<br>
           <input type="file" name="myfile"><br>
           <br>
           <input type="submit" name="submit" value="Commit">
        </form>
    </body>
    </html>
     
    demo2.jsp
    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <%@ page import="org.apache.commons.fileupload.*"%>
    <%@ page import="org.apache.commons.fileupload.servlet.*"%>
    <%@ page import="org.apache.commons.fileupload.disk.*"%>
    <%@ page import="java.util.*"%>
    <%@ page import="java.io.*"%>
     
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%String uploadPath="D:""temp";
     boolean isMultipart = ServletFileUpload.isMultipartContent(request);
     if(isMultipart==true){
         try{
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);//得到所有的文件
           Iterator<FileItem> itr = items.iterator();
            while(itr.hasNext()){//依次處理每個文件
            FileItem item=(FileItem)itr.next();
            String fileName=item.getName();//獲得文件名,包括路徑
            if(fileName!=null){
                File fullFile=new File(item.getName());
                File savedFile=new File(uploadPath,fullFile.getName());
                item.write(savedFile);
            }
            }
            out.print("upload succeed");
         }
         catch(Exception e){
            e.printStackTrace();
         }
     }
     else{
         out.println("the enctype must be multipart/form-data");
     }
    %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>File upload</title>
    </head>
    <body>
    </body>
    </html>
    結果:
    upload succeed
    此時,在"D:"temp"下可以看到你上傳的兩個文件。
    示例3
    上傳一個文件到指定的目錄,并限定文件大小。
    demo3.html
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
        <title>File upload</title>
    </head>
    <body>
        <form name="myform" action="demo3.jsp" method="post"
           enctype="multipart/form-data">
           File:<br>
           <input type="file" name="myfile"><br>
           <br>
           <input type="submit" name="submit" value="Commit">
        </form>
    </body>
    </html>
     
    demo3.jsp
    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <%@ page import="org.apache.commons.fileupload.*"%>
    <%@ page import="org.apache.commons.fileupload.servlet.*"%>
    <%@ page import="org.apache.commons.fileupload.disk.*"%>
    <%@ page import="java.util.*"%>
    <%@ page import="java.io.*"%>
     
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%
        File uploadPath = new File("D:""temp");//上傳文件目錄
        if (!uploadPath.exists()) {
           uploadPath.mkdirs();
        }
        // 臨時文件目錄
        File tempPathFile = new File("d:""temp""buffer""");
        if (!tempPathFile.exists()) {
           tempPathFile.mkdirs();
        }
        try {
           // Create a factory for disk-based file items
           DiskFileItemFactory factory = new DiskFileItemFactory();
     
           // Set factory constraints
           factory.setSizeThreshold(4096); // 設置緩沖區大小,這里是4kb
           factory.setRepository(tempPathFile);//設置緩沖區目錄
     
           // Create a new file upload handler
           ServletFileUpload upload = new ServletFileUpload(factory);
     
           // Set overall request size constraint
           upload.setSizeMax(4194304); // 設置最大文件尺寸,這里是4MB
     
           List<FileItem> items = upload.parseRequest(request);//得到所有的文件
           Iterator<FileItem> i = items.iterator();
           while (i.hasNext()) {
               FileItem fi = (FileItem) i.next();
               String fileName = fi.getName();
               if (fileName != null) {
           File fullFile = new File(fi.getName());
           File savedFile = new File(uploadPath, fullFile
                  .getName());
           fi.write(savedFile);
               }
           }
           out.print("upload succeed");
        } catch (Exception e) {
           e.printStackTrace();
        }
    %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>File upload</title>
    </head>
    <body>
    </body>
    </html>
    示例4
    利用Servlet來實現文件上傳。
    Upload.java
    package com.zj.sample;
     
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
     
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
     
    @SuppressWarnings("serial")
    publicclass Upload extends HttpServlet {
        private String uploadPath = "D:""temp"; // 上傳文件的目錄
        private String tempPath = "d:""temp""buffer"""; // 臨時文件目錄
        File tempPathFile;
     
        @SuppressWarnings("unchecked")
        publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
               throws IOException, ServletException {
           try {
               // Create a factory for disk-based file items
               DiskFileItemFactory factory = new DiskFileItemFactory();
     
               // Set factory constraints
               factory.setSizeThreshold(4096); // 設置緩沖區大小,這里是4kb
               factory.setRepository(tempPathFile);// 設置緩沖區目錄
     
               // Create a new file upload handler
               ServletFileUpload upload = new ServletFileUpload(factory);
     
               // Set overall request size constraint
               upload.setSizeMax(4194304); // 設置最大文件尺寸,這里是4MB
     
               List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
               Iterator<FileItem> i = items.iterator();
               while (i.hasNext()) {
                  FileItem fi = (FileItem) i.next();
                  String fileName = fi.getName();
                  if (fileName != null) {
                      File fullFile = new File(fi.getName());
                      File savedFile = new File(uploadPath, fullFile.getName());
                      fi.write(savedFile);
                  }
               }
               System.out.print("upload succeed");
           } catch (Exception e) {
               // 可以跳轉出錯頁面
               e.printStackTrace();
           }
        }
     
        publicvoid init() throws ServletException {
           File uploadFile = new File(uploadPath);
           if (!uploadFile.exists()) {
               uploadFile.mkdirs();
           }
           File tempPathFile = new File(tempPath);
            if (!tempPathFile.exists()) {
               tempPathFile.mkdirs();
           }
        }
    }
     
    demo4.html
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
        <title>File upload</title>
    </head>
    <body>
    // action="fileupload"對應web.xml<servlet-mapping><url-pattern>的設置.
        <form name="myform" action="fileupload" method="post"
           enctype="multipart/form-data">
           File:<br>
           <input type="file" name="myfile"><br>
           <br>
           <input type="submit" name="submit" value="Commit">
        </form>
    </body>
    </html>
     
    web.xml
    <servlet>
        <servlet-name>Upload</servlet-name>
        <servlet-class>com.zj.sample.Upload</servlet-class>
    </servlet>
     
    <servlet-mapping>
        <servlet-name>Upload</servlet-name>
        <url-pattern>/fileupload</url-pattern>
    </servlet-mapping>

    本文出自 “子 孑” 博客,請務必保留此出處http://zhangjunhd.blog.51cto.com/113473/18331

    本文出自 51CTO.COM技術博客

    附件下載:
      fileUpload工程
    posted on 2010-01-19 23:26 小菜毛毛 閱讀(1141) 評論(3)  編輯  收藏 所屬分類: J2EE相關技術與框架

    Feedback

    # re: Apache Commons fileUpload實現文件上傳 2010-01-20 01:09 小菜毛毛
    非常的有用,我自己項目中就是這樣用的  回復  更多評論
      

    # re: Apache Commons fileUpload實現文件上傳 2010-01-20 01:14 小菜毛毛
    這里附上需用到的JAR包,新手的話需要找半天 呵呵
    http://www.tkk7.com/Files/caizh2009/commons-io-1.4-bin.zip

    http://www.tkk7.com/Files/caizh2009/commons-fileupload-1.2.1-bin.zip
      回復  更多評論
      

    # re: Apache Commons fileUpload實現文件上傳 2016-06-13 23:16 未來不是夢
    good  回復  更多評論
      

    主站蜘蛛池模板: 日韩精品无码免费专区午夜 | 亚洲成AV人片在| 曰批视频免费40分钟试看天天| tom影院亚洲国产一区二区| 四虎永久在线免费观看| 国产成人免费AV在线播放| 欧洲 亚洲 国产图片综合| 三上悠亚亚洲一区高清| 国产免费久久精品99re丫y| 又黄又大的激情视频在线观看免费视频社区在线 | 无人视频免费观看免费视频| 亚洲av日韩av天堂影片精品| 女人18毛片水真多免费看| 久久一区二区免费播放| jlzzjlzz亚洲jzjzjz| 久久亚洲中文字幕精品一区| 和日本免费不卡在线v| 亚洲国产免费综合| 亚洲天堂免费在线| 亚洲Av综合色区无码专区桃色| 香蕉高清免费永久在线视频 | 亚洲粉嫩美白在线| 亚洲av无码国产精品色午夜字幕| 免费黄色app网站| 久久99国产综合精品免费| 一级毛片a免费播放王色电影 | 亚洲日本中文字幕天天更新| 国产亚洲精品观看91在线| 免费观看的毛片手机视频| 91在线老王精品免费播放| 一本一道dvd在线观看免费视频 | 国产乱人免费视频| 免费在线观看h片| 日批视频网址免费观看| jizzjizz亚洲日本少妇| 亚洲伊人久久大香线焦| 久久久影院亚洲精品| 久久亚洲国产成人影院网站| 国产在线19禁免费观看| 国产1024精品视频专区免费| 先锋影音资源片午夜在线观看视频免费播放 |