使用commons-fileupload上传文件到服务器

转自http://blog.csdn.net/lcyong_/article/details/70227161

需要的jar

commons-fileupload-1.3.2

commons-io-1.4

servlet-api

特别注意commons-fileupload使用的时候必须和commons-io一起, 注意版本,其他版本容易报错



1  新建project并导入jar包

2 新建jsp文件index.jsp如下:


[html] view plain copy
print ?
  1. <%@ page language=“java” import=“java.util.*” pageEncoding=“UTF-8”%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;  
  5. %>  
  6. >  
  7. <html>  
  8.   <head>  
  9.     <base href=“<%=basePath%>”>  
  10.     <title>文件上传title>  
  11.       <script type=“text/javascript” language=“JavaScript”>  
  12.           function prom() {  
  13.               window.open(“upload.jsp”,”_blank”,”height=400,width=500“)  
  14.   
  15.           }  
  16.       script>  
  17.   head>  
  18.   <body>  
  19.   <button value=“上传文件”>button>  
  20.   <input type=“button” value=“upload” onclick=“prom()”/>  
  21.   body>  
  22. html>  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


  
    
    文件上传
      
  
  
  
  
  




3 点击上传文件的时候弹窗出对话框   新建jsp文件upload.jsp

[html] view plain copy
print ?
  1. <%  
  2.     String path = request.getContextPath();  
  3.     String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;  
  4. %>  
  5. <base href=“<%=basePath%>”>  
  6. <form method=“post” action=“UploadServlet” enctype=“multipart/form-data”>  
  7.     <table width=“400” height=“200”>  
  8.         <tr>  
  9.             <td height=“20”>td>  
  10.         tr>  
  11.         <tr>  
  12.             <td height=“20”>td>  
  13.         tr>  
  14.         <tr>  
  15.             <td align=“center”>选择上传文件:(文件大小不要超过2MB)td>  
  16.         tr>  
  17.         <tr>  
  18.             <td align=“center”> <input type=“file” name=“file1” size=“50” value=“选择文件”>td>  
  19.         tr>  
  20.         <tr>  
  21.             <td align=“center”> <input type=“submit” value=“开始上传”>td>  
  22.   
  23.         tr>  
  24.         <tr>  
  25.             <td height=“40”>td>  
  26.         tr>  
  27.     table>  
  28. form>  
  29. 结果:<%=request.getAttribute(“result”)%>  
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

选择上传文件:(文件大小不要超过2MB)
结果:<%=request.getAttribute("result")%>



4 在新建一个servlet    UploadServlet


[java] view plain copy
print ?
  1. package com.lh.servlet;  
  2.   
  3. import java.io.*;  
  4. import java.util.*;  
  5. import org.apache.commons.fileupload.*;  
  6. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  7. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  8.   
  9. import javax.servlet.*;  
  10. import javax.servlet.http.*;  
  11.   
  12. public class UploadServlet extends HttpServlet {  
  13.   
  14.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  15.             throws ServletException, IOException {  
  16.         request.setCharacterEncoding(”UTF-8”);  
  17.         String Path=getServletContext().getRealPath(”/”)+“upload”;          //定义上传文件的地址  
  18.   
  19.         System.out.print(Path);  
  20.         File folder = new File(Path);  
  21.         if(!folder.exists())  
  22.             folder.mkdirs();  
  23.         String message=null;  
  24.         if(ServletFileUpload.isMultipartContent(request)){  //判断是否获取的是文件  
  25.             DiskFileItemFactory disk=new DiskFileItemFactory();  
  26.             disk.setSizeThreshold(20*1024);                 //设置内存可存字节数  
  27.             disk.setRepository(disk.getRepository());       //设置临时文件目录  
  28.             ServletFileUpload up=new ServletFileUpload(disk);  
  29.             int maxsize=200*1024*1024;  
  30.             List list=null;  
  31.             try{  
  32.                 System.err.print(”—————–”);  
  33.                 list=up.parseRequest(request);              //获取上传列表  
  34.             }  
  35.             catch(Exception e){  
  36.                 e.printStackTrace();  
  37.             }  
  38.             Iterator i=list.iterator();                     //创建列表的迭代器  
  39.             while(i.hasNext()){  
  40.                 FileItem fm=(FileItem)i.next();             //遍历列表  
  41.                 if(!fm.isFormField()){  
  42.                     String fname=fm.getName();              //获取文件名  
  43.                     String filePath =fm.getName();  //获取文件全路径名  
  44.                     String fileName=”“;  
  45.                     int startIndex = filePath.lastIndexOf(“\\”);  
  46.                     if(startIndex!=-1){                     //对文件名进行截取  
  47.                         fileName = filePath.substring(startIndex+1);  
  48.                     }else{  
  49.                         fileName=filePath;  
  50.                     }  
  51.                     if(fm.getSize()>maxsize){  
  52.                         message=”文件太大了,不要超过200MB”;  
  53.                         break;  
  54.                     }  
  55.                     String fileSize=new Long(fm.getSize()).toString();  
  56.                     if((fname==null)||(fname.equals(“”))&&(fileSize.equals(“0”))){  
  57.                         message=”文件名不能为空,文件大小也不能为零!”;  
  58.                         break;  
  59.                     }  
  60.                     File saveFile=new File(Path,fileName);  
  61.                     try{  
  62.                         fm.write(saveFile);//向文件中写入数据  
  63.                          
  64.                         message=”文件上传成功!”;  
  65.   
  66.                     }  
  67.                     catch(Exception e1){  
  68.                         e1.printStackTrace();  
  69.                     }  
  70.                 }  
  71.             }  
  72.         }  
  73.         request.setAttribute(”result”,message);  
  74.         RequestDispatcher rd=request.getRequestDispatcher(”upload.jsp”);  
  75.         rd.forward(request, response);  
  76.   
  77.     }  
  78.   
  79.     public void init(ServletConfig config) throws ServletException {  
  80.         super.init(config);  
  81.     }  
  82.     
  83. }  
package com.lh.servlet;

import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;

public class UploadServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String Path=getServletContext().getRealPath("/")+"upload";          //定义上传文件的地址

        System.out.print(Path);
        File folder = new File(Path);
        if(!folder.exists())
            folder.mkdirs();
        String message=null;
        if(ServletFileUpload.isMultipartContent(request)){  //判断是否获取的是文件
            DiskFileItemFactory disk=new DiskFileItemFactory();
            disk.setSizeThreshold(20*1024);                 //设置内存可存字节数
            disk.setRepository(disk.getRepository());       //设置临时文件目录
            ServletFileUpload up=new ServletFileUpload(disk);
            int maxsize=200*1024*1024;
            List list=null;
            try{
                System.err.print("-----------------");
                list=up.parseRequest(request);              //获取上传列表
            }
            catch(Exception e){
                e.printStackTrace();
            }
            Iterator i=list.iterator();                     //创建列表的迭代器
            while(i.hasNext()){
                FileItem fm=(FileItem)i.next();             //遍历列表
                if(!fm.isFormField()){
                    String fname=fm.getName();              //获取文件名
                    String filePath =fm.getName();  //获取文件全路径名
                    String fileName="";
                    int startIndex = filePath.lastIndexOf("\\");
                    if(startIndex!=-1){                     //对文件名进行截取
                        fileName = filePath.substring(startIndex+1);
                    }else{
                        fileName=filePath;
                    }
                    if(fm.getSize()>maxsize){
                        message="文件太大了,不要超过200MB";
                        break;
                    }
                    String fileSize=new Long(fm.getSize()).toString();
                    if((fname==null)||(fname.equals(""))&&(fileSize.equals("0"))){
                        message="文件名不能为空,文件大小也不能为零!";
                        break;
                    }
                    File saveFile=new File(Path,fileName);
                    try{
                        fm.write(saveFile);//向文件中写入数据

                        message="文件上传成功!";

                    }
                    catch(Exception e1){
                        e1.printStackTrace();
                    }
                }
            }
        }
        request.setAttribute("result",message);
        RequestDispatcher rd=request.getRequestDispatcher("upload.jsp");
        rd.forward(request, response);

    }

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

}


5  在web.xml文件中配置如下:

[html] view plain copy
print ?
  1. <servlet>  
  2.    <description>UploadServletdescription>  
  3.    <display-name>UploadServletdisplay-name>  
  4.    <servlet-name>UploadServletservlet-name>  
  5.    <servlet-class>com.lh.servlet.UploadServletservlet-class>  
  6.  servlet>  
  7.   
  8.  <servlet-mapping>  
  9.    <servlet-name>UploadServletservlet-name>  
  10.    <url-pattern>/UploadServleturl-pattern>  
  11.  servlet-mapping>  
  12.  <welcome-file-list>  
  13.    <welcome-file>index.jspwelcome-file>  
  14.  welcome-file-list>  
 
    UploadServlet
    UploadServlet
    UploadServlet
    com.lh.servlet.UploadServlet
  

  
    UploadServlet
    /UploadServlet
  
  
    index.jsp
  




你可能感兴趣的:(使用commons-fileupload上传文件到服务器)