用Common FileUpload 实现文件的上传

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

Apache common fileUpload 来实现!本文采用的jsp+servlet 来实现的上传,并将文件存储到服务器端!

          看一下项目的布局,可以看到要引用两个文件,commons-fileupload-1.3.1.jar 和commons-io-1.3.2.jar ,这两个文件 直接去官网就可以下载,很好找到!

       

         我们先来看一下FileUpload.jsp的页面代码!一定要注意form的提交方式为post 提交,编码类型为enctype="multipart/form-data"编码格式。 本例子是实现的图片的上传,所以对图片的格式进行了验证,其他文件类型的上传同样的验证方式就可以,不过要改一下文件后缀名!

<%@ 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>  
<script type="text/javascript">  
    //指定允许的上传文件类型  
    var extArray = new Array(".jpg",".png",".jpeg",".gif");  
    var allowFormSubmit=false;  
    //有哪些限制  
    function LimitAttach(form, file){  
        var allowSubmit = false;  
        if (!file){  
            alert("请先选择文件,然后在上传!");  
            return;  
        }  
        while (file.indexOf("\\") != -1){  
            file = file.slice(file.indexOf("\\") + 1);  
        }  
        var ext = file.slice(file.indexOf(".")).toLowerCase();  
        for (var i = 0; i < extArray.length; i++) {  
            if (extArray[i] == ext){  
                allowSubmit = true;  
                break;  
            }  
        }  
        if (allowSubmit){  
            //符合条件, 发给指定的servlet   
            form.submit();  
            form.method="post";  
            form.action="servlet/UploadHandleServlet";  
              
        }else{ //检测上传文件类型  
              
            alert("只能上传以下格式的文件:"+ (extArray.join("")) + "\n请重新选择再上传.");  
        }  
    }  
</script>  
</head>  
<body>  
    <form name="upform"  target="_self" id="uploadForm" enctype="multipart/form-data">  
    <input name="uploadfile" size="40" type="file" >   
    <input name="upload" type="submit" onclick="LimitAttach(this.form,this.form.uploadfile.value)" value="上传"/>  
    </form>  
</body>  
</html> 

     而在servlet 端 的工作过程是1. 创建一个文件的解析对象, 然后对上传文件的大小做一个限制, 获取上传文件, 将文件存储服务器的文件夹中! 下边看一下servlet的代码, servlet的使用要在配置文件中进行配置!具体如何配置 就参见百度! 这里不再介绍!
package com.tgb.test.Servlet;  
  
import java.io.File;  
import java.io.IOException;  
import java.io.PrintWriter;  
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;  
  
public class UploadHandleServlet extends HttpServlet {  
  
    private File uploadPath;  
    private File tempPath;  
      
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        //1 创建文件解析对象  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
        factory.setSizeThreshold(4096);  
        factory.setRepository(tempPath);  
  
        ServletFileUpload upload = new ServletFileUpload(factory);  
        upload.setSizeMax(1000000 * 20);  
        try {  
            //获取上传文件   
            List fileItems = upload.parseRequest(request);  
            String itemNo = "";  
            for (Iterator iter = fileItems.iterator(); iter.hasNext();) {  
                FileItem item = (FileItem) iter.next();  
  
                //是普通的表单输入域  
                if(item.isFormField()) {  
                    if ("itemNo".equals(item.getFieldName())) {  
                        itemNo = item.getString();  
                    }  
                }  
                //是否为input="type"输入域  
                if (!item.isFormField()) {  
                    String fileName = item.getName();  
                    long size = item.getSize();  
                    if ((fileName == null || fileName.equals("")) && size == 0) {  
                        continue;  
                    }  
                    //截取字符串 如:C:\WINDOWS\Debug\PASSWD.LOG  
                    fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());  
                    //将文件存入指定的文件  
                    item.write(new File(uploadPath, fileName));  
                }  
            }  
              
            response.sendRedirect(request.getContextPath() + "/index.jsp?flag='成功!'");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
    }  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doGet(request, response);  
    }  
    public void init() throws ServletException {  
        //itemManager= new ItemManagerImpl();  
        uploadPath = new File(getServletContext().getRealPath("upload"));  
        System.out.println("uploadPath=====" + uploadPath);  
        //如果目录不存在  
        if (!uploadPath.exists()) {  
                //创建目录  
            uploadPath.mkdir();  
        }  
                  
        //临时目录  
        tempPath = new File(getServletContext().getRealPath("temp"));  
        if (!tempPath.exists()) {  
            tempPath.mkdir();  
        }  
    }  
  
}  

  这样一个简单的文件的上传功能就完成了。我们还可以同事上传多个文件,如果使用spring mvc ,他还自己封装了更简单的实现方法!