最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Apache commons fileupload文件上傳實例講解

 更新時間:2016年10月14日 16:09:58   作者:xingoo  
這篇文章主要為大家詳細(xì)介紹了Apache commons fileupload文件上傳實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下

文件上傳的方法主要目前有兩個常用的,一個是SmartUpload,一個是Apache的Commons fileupload.

我們這里主要介紹下第二個的用法,首先要上傳文件,注意幾個問題:

  1 form表單內(nèi),要添加空間<input type="file" name="myfile">

  2 form表單的內(nèi)容格式要定義成multipart/form-data格式

  3 需要類庫:1 commons-io.jar 2commons-fileupload-1.3.1.jar

接下來我們看下用法。

首先閱讀Apache commons fileupload的官方文檔可以發(fā)現(xiàn)下面幾個常用的函數(shù):

1 創(chuàng)建文件解析對象

復(fù)制代碼 代碼如下:
DiskFileUpload diskFileUpload = new DiskFileUpload();

2 進(jìn)行文件解析后放在List中,因為這個類庫支持多個文件上傳,因此把結(jié)果會存在List中。

復(fù)制代碼 代碼如下:
List<FileItem> list = diskFileUpload.parseRequest(request);

3 獲取上傳文件,進(jìn)行分析(不是必須)

復(fù)制代碼 代碼如下:
File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));

4 創(chuàng)建新對象,進(jìn)行流拷貝

file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
            file1.getParentFile().mkdirs();
            file1.createNewFile();
            
            InputStream ins = fileItem.getInputStream();
            OutputStream ous = new FileOutputStream(file1);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while((len = ins.read(buffer)) > -1)
                ous.write(buffer,0,len);
              out.println("以保存文件"+file1.getAbsolutePath()+"<br/>");
            }finally{
              ous.close();
              ins.close();
            }

這樣我們就完成了文件的上傳。

fileUpload.html

 <form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
    <div align="center">
      <fieldset style="width:80%">
        <legend>上傳文件</legend><br/>
          <div align="left">上傳文件1</div>
          <div align="left">
            <input type="file" name="file1"/>
          </div>
          <div align="left">上傳文件2</div>
          <div align="left">
            <input type="file" name="file2"/>
          </div>
          <div>
            <div align='left'>上傳文件說明1</div>
            <div align='left'><input type="text" name="description1"/></div>
          </div>
          <div>
            <div align='left'>上傳文件說明2</div>
            <div align='left'><input type="text" name="description2"/></div>
          </div>
          <div>
            <div align='left'>
              <input type='submit' value="上傳文件"/>
            </div>
          </div>
      </fieldset>
    </div>
  </form>

web.xml

<servlet>
  <servlet-name>UploadServlet</servlet-name>
  <servlet-class>com.test.hello.UploadServlet</servlet-class>
 </servlet>
<servlet-mapping>
  <servlet-name>UploadServlet</servlet-name>
  <url-pattern>/servlet/UploadServlet</url-pattern>
 </servlet-mapping>

UploadServlet.java

package com.test.hello;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

public class UploadServlet extends HttpServlet {

  /**
   * Constructor of the object.
   */
  public UploadServlet() {
    super();
  }

  /**
   * Destruction of the servlet. <br>
   */
  public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
  }

  /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   * 
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setCharacterEncoding("UTF-8");
    response.getWriter().println("請以POST方式上傳文件");
  }

  /**
   * The doPost method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to post.
   * 
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  @SuppressWarnings({ "unchecked", "deprecation" })
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    File file1 = null,file2=null;
    String description1 = null,description2 = null;
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    
    DiskFileUpload diskFileUpload = new DiskFileUpload();
    try{
      List<FileItem> list = diskFileUpload.parseRequest(request);
      
      out.println("遍歷所有的FileItem...<br/>");
      for(FileItem fileItem : list){
        if(fileItem.isFormField()){
          if("description1".equals(fileItem.getFieldName())){
            out.println("遍歷到description1 ... <br/>");
            description1 = new String(fileItem.getString().getBytes(),"UTF-8");
          }
          if("description2".equals(fileItem.getFieldName())){
            out.println("遍歷到description2 ... <br/>");
            description2 = new String(fileItem.getString().getBytes(),"UTF-8");
          }
        }else{
          if("file1".equals(fileItem.getFieldName())){
            File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
            out.println("遍歷到file1...<br/>");
            out.println("客戶端文件位置:"+remoteFile.getAbsolutePath()+"<br/>");
            
            file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
            file1.getParentFile().mkdirs();
            file1.createNewFile();
            
            InputStream ins = fileItem.getInputStream();
            OutputStream ous = new FileOutputStream(file1);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while((len = ins.read(buffer)) > -1)
                ous.write(buffer,0,len);
              out.println("以保存文件"+file1.getAbsolutePath()+"<br/>");
            }finally{
              ous.close();
              ins.close();
            }
          }
          if("file2".equals(fileItem.getFieldName())){
            File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
            out.println("遍歷到file2...<br/>");
            out.println("客戶端文件位置:"+remoteFile.getAbsolutePath()+"<br/>");
            
            file2 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
            file2.getParentFile().mkdirs();
            file2.createNewFile();
            
            InputStream ins = fileItem.getInputStream();
            OutputStream ous = new FileOutputStream(file2);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while((len = ins.read(buffer)) > -1)
                ous.write(buffer,0,len);
              out.println("以保存文件"+file2.getAbsolutePath()+"<br/>");
            }finally{
              ous.close();
              ins.close();
            }
          }
        }
        out.println("Request 解析完畢<br/><br/>");
      }
    }catch(FileUploadException e){}
    
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    out.println("<HTML>");
    out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
    out.println(" <BODY>");
    
    if(file1 != null){
      out.println("<div>");
      out.println(" <div align='left'>file1;</div>");
      out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+
          file1.getName()+"'target=_blank>"+file1.getName()+"</a>");
      out.println("</div>");
      out.println("</div>");
    }
    if(file2 != null){
      out.println("<div>");
      out.println(" <div align='left'>file2;</div>");
      out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+
          file2.getName()+"'target=_blank>"+file2.getName()+"</a>");
      out.println("</div>");
      out.println("</div>");
    }
    out.println("<div>");
    out.println(" <div align='left'>description1:</div>");
    out.println(" <div align='left'>");
    out.println(description1);
    out.println("</div>");
    out.println("</div>");
    
    out.println("<div>");
    out.println(" <div align='left'>description2:</div>");
    out.println(" <div align='left'>");
    out.println(description2);
    out.println("</div>");
    out.println("</div>");
    
    out.println(" </BODY>");
    out.println("</HTML>");
    out.flush();
    out.close();
  }

  /**
   * Initialization of the servlet. <br>
   *
   * @throws ServletException if an error occurs
   */
  public void init() throws ServletException {
    // Put your code here
  }

}

運行示例

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java簡單工廠模式實例及講解

    java簡單工廠模式實例及講解

    這篇文章主要為大家詳細(xì)介紹了java簡單工廠模式實例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Java使用ES?Client?調(diào)用滾動查詢及Elasticsearch滾動查詢Scrolling機(jī)制

    Java使用ES?Client?調(diào)用滾動查詢及Elasticsearch滾動查詢Scrolling機(jī)制

    Elasticsearch提供了一種稱為"滾動查詢"(Scrolling)的機(jī)制,用于處理大型數(shù)據(jù)集的分頁查詢,這篇文章給大家介紹滾動查詢的一般步驟及Java使用ESClient調(diào)用滾動查詢的方法,感興趣的朋友一起看看吧
    2023-08-08
  • Java多線程CAS操作原理代碼實例解析

    Java多線程CAS操作原理代碼實例解析

    這篇文章主要介紹了Java多線程CAS操作原理代碼實例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • Mybatis 動態(tài)sql if 判讀條件等于一個數(shù)字的案例

    Mybatis 動態(tài)sql if 判讀條件等于一個數(shù)字的案例

    這篇文章主要介紹了Mybatis 動態(tài)sql if 判讀條件等于一個數(shù)字的案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • Java中的CountDownLatch閉鎖詳解

    Java中的CountDownLatch閉鎖詳解

    這篇文章主要介紹了Java中的CountDownLatch閉鎖詳解,CountDownLatch用給定的計數(shù)初始化,await屬于阻塞方法,直到當(dāng)前計數(shù)達(dá)到零,由于countDown方法被調(diào)用,然后釋放所有await等待的線程,并立即返回線程后續(xù)的await調(diào)用邏輯,需要的朋友可以參考下
    2023-12-12
  • 解決異常FileNotFoundException:class path resource找不到資源文件的問題

    解決異常FileNotFoundException:class path resource找不到資源文件的問題

    今天小編就為大家分享一篇關(guān)于解決異常FileNotFoundException:class path resource找不到資源文件的問題,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • java常見報錯:Array?Out?of?Bounds兩種解決辦法

    java常見報錯:Array?Out?of?Bounds兩種解決辦法

    這篇文章主要給大家介紹了關(guān)于java報錯Array?Out?of?Bounds的兩種解決辦法,Array out of bounds錯誤表示你嘗試訪問數(shù)組中不存在的索引,即索引小于零或者大于等于數(shù)組的大小,文中通過代碼將解決的辦法介紹的非常詳細(xì),需要的朋友可以參考下
    2024-08-08
  • 詳解MyBatis的XML實現(xiàn)方法(附帶注解方式實現(xiàn))

    詳解MyBatis的XML實現(xiàn)方法(附帶注解方式實現(xiàn))

    這篇文章主要詳細(xì)介紹了MyBatis的XML實現(xiàn)方法(附帶注解方式實現(xiàn)),文中通過代碼示例給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-05-05
  • 解決Properties屬性文件中的值有等號和換行的小問題

    解決Properties屬性文件中的值有等號和換行的小問題

    這篇文章主要介紹了解決Properties屬性文件中的值有等號有換行的小問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Spring?Boot在開發(fā)過程中常用IDEA插件

    Spring?Boot在開發(fā)過程中常用IDEA插件

    這篇文章主要為大家介紹了Spring?Boot在開發(fā)過程中常用IDEA插件,幫助大家提高開發(fā)工作效率,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2022-03-03

最新評論

阿拉善左旗| 巴彦淖尔市| 龙州县| 瓦房店市| 安阳市| 滦南县| 长汀县| 北流市| 石台县| 原平市| 竹北市| 连南| 光山县| 铜陵市| 阿巴嘎旗| 运城市| 宣汉县| 宿松县| 尼木县| 稻城县| 铜鼓县| 静宁县| 江川县| 襄樊市| 胶南市| 沾益县| 固安县| 屯门区| 河源市| 萍乡市| 凤山市| 萨嘎县| 清丰县| 蒙城县| 海口市| 安塞县| 滨州市| 海门市| 诏安县| 英山县| 监利县|