程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Apache Commons fileUpload文件上傳多個示例分享

Apache Commons fileUpload文件上傳多個示例分享

編輯:關於JAVA

Apache Commons fileUpload文件上傳多個示例分享。本站提示廣大學習愛好者:(Apache Commons fileUpload文件上傳多個示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是Apache Commons fileUpload文件上傳多個示例分享正文


本文經由過程實例來引見若何應用commons-fileupload.jar,Apache的commons-fileupload.jar可便利的完成文件的上傳功效,詳細內容以下

將Apache的commons-fileupload.jar放在運用法式的WEB-INF\lib下,便可應用。上面舉例引見若何應用它的文件上傳功效。

所應用的fileUpload版本為1.2,情況為Eclipse3.3+MyEclipse6.0。FileUpload 是基於 Commons IO的,所以在進入項今朝先肯定Commons IO的jar包(本文應用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.html中type="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")
public class Upload extends HttpServlet {
  private String uploadPath = "D:\\temp"; // 上傳文件的目次
  private String tempPath = "d:\\temp\\buffer\\"; // 暫時文件目次
  File tempPathFile;
 
  @SuppressWarnings("unchecked")
  public void 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();
    }
  }
 
  public void 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>

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved