Apache common-fileupload 组件的使用实例

    xiaoxiao2025-01-17  13

    一、对于web页面文件上传实现有多种方式,jsp页面的文件上传有多种实现方式,包括JSP自身的smartUpload组件,但是smartUpload组件也逐渐的被放弃了,

            取而代之的是Apache开源组件common-fileupload组件,该组件不管是在Spring框架(framework)或者在Struts2中都有用到并且很受欢迎。

    二、下面对于改组件的使用介绍一个实例,希望网友能够喜欢         环境:Myeclipse7.5+JDK1.6+common-fileUpload.jar+common-io.jar(两个jar自己download吧,上apache网站)        第一步:在Myeclise中新建web project

             第二步:导入依赖的两个apache jar包

    三、下面是代码部分,直接上代码

       1、新建类UploadServlet,继承自HttpServlet

    package com.deppon.test; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletContext; 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.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadServlet extends HttpServlet {  @SuppressWarnings("deprecation")  @Override  protected void doPost(HttpServletRequest request,    HttpServletResponse response) throws ServletException, IOException {   DiskFileItemFactory factory = new DiskFileItemFactory();   factory.setSizeThreshold(4 * 1024);   ServletFileUpload upload = new ServletFileUpload(factory);   upload.setSizeMax(1000 * 1024 * 1024);   List itemList = null;   try {    itemList = upload.parseRequest(request);   } catch (FileUploadBase.SizeLimitExceededException e) {    // 请求数据的size超出了规定的大小.    e.printStackTrace();    request.setAttribute("uploadError", "请求数据的size超出了规定的大小");    request.getRequestDispatcher("/uploadError.jsp").forward(request,      response);    return;   } catch (FileUploadBase.InvalidContentTypeException e) {    // 无效的请求类型,即请求类型enctype != "multipart/form-data"    request.setAttribute("uploadError",      "请求类型enctype != multipart/form-data");    request.getRequestDispatcher("/uploadError.jsp").forward(request,      response);    return;   } catch (FileUploadException e) {    // 如果都不是以上子异常,则抛出此总的异常,出现此异常原因无法说明.    request.setAttribute("uploadError", "上传过程异常,导致其原因可能是磁盘已满或者其它原因");    request.getRequestDispatcher("/uploadError.jsp").forward(request,      response);    return;   }   if (itemList != null) {    Iterator it = itemList.iterator();    while (it.hasNext()) {     FileItem item = (FileItem) it.next();     if (item.isFormField()) {      System.out.println(item.getFieldName());      if ("fileName".equals(item.getFieldName())) {       request.setAttribute("fileName", item         .getString("GB18030"));       System.out.println(item.getString("GBK"));      }     } else {      String uploadPath = request.getRealPath("/upload");      String totalName = item.getName();      String name = "temp";      if (totalName != "") {       int index = totalName.lastIndexOf("\");       name = totalName.substring(index + 1);       System.out.println(name);      } else {       name = "temp";      }      String path = uploadPath + "/" + name;      try {       item.write(new File(path));      } catch (Exception e) {       // TODO Auto-generated catch block       e.printStackTrace();       request.setAttribute("uploadError", "写入磁盘错误");       request.getRequestDispatcher("/uploadError.jsp")         .forward(request, response);       return;      }     }    }   } else {    request.setAttribute("uploadError", "上传数据空");    request.getRequestDispatcher("/uploadError.jsp").forward(request,      response);    return;   }   request.getRequestDispatcher("/uploadSuccess.jsp").forward(request,     response);  }

    }

    二、配置改servlet,在web.xml中

        <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5"  xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">   <servlet>     <description>This is the description of my J2EE component</description>     <display-name>This is the display name of my J2EE component</display-name>     <servlet-name>UploadServlet</servlet-name>     <servlet-class>com.deppon.test.UploadServlet</servlet-class>   </servlet>   <servlet-mapping>     <servlet-name>UploadServlet</servlet-name>     <url-pattern>/servlet/UploadServlet</url-pattern>   </servlet-mapping>   <welcome-file-list>     <welcome-file>index.jsp</welcome-file>   </welcome-file-list>

    </web-app>

    三、新建三个JSP文件,index.jsp,uploadSuccess.jsp,uploadError.jsp

        1、index.jsp

        <%@ page language="java" contentType="text/html; charset=GB18030"  pageEncoding="GB18030"%> <!DOCTYPE html PubLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html>  <head>   <meta http-equiv="Content-Type" content="text/html; charset=GB18030">   <title>Insert title here</title>  </head>  <body>   <form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">    上传文件1:    <input type="file" name="fileUpload">    <br>    上传文件2:    <input type="file" name="fileUpload1">    <br>    测试表单域:    <input type="text" name="fileName">    <br>    <input type="submit" value="上传">   </form>  </body>

    </html>

       2、uploadSuccess.jsp

       <%@ page language="java" contentType="text/html; charset=GB18030"  pageEncoding="GB18030"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html>  <head>   <meta http-equiv="Content-Type" content="text/html; charset=GB18030">   <title>Insert title here</title>  </head>  <body>   上传成功   <br>   其中的字段fileName:${fileName}  </body>

    </html>

       3、uploadError.jsp

       <%@ page language="java" contentType="text/html; charset=GB18030"  pageEncoding="GB18030"%> <!DOCTYPE html P LIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html>  <head>   <meta http-equiv="Content-Type" content="text/html; charset=GB18030">   <title>Insert title here</title>  </head>  <body>   ${uploadError}  </body> </html> 四、部署到tomcat或者Jboss,都可以 五、启动tomcat或jboss,访问该应用 http://localhost:8080/fileUpload/index.jsp,你会发现惊喜!!
    转载请注明原文地址: https://ju.6miu.com/read-1295577.html
    最新回复(0)