fileupload上传代码

来源:互联网 发布:电子地图 数据采集 编辑:程序博客网 时间:2024/05/01 06:59
fileupload上传代码

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import java.net.ResponseCache;

import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

/*
 * 创建日期 2005-4-10
 *
 * TODO 要更改此生成的文件的模板,请转至
 * 窗口 - 首选项 - Java - 代码样式 -代码模板
 
*/


/**
 * 
@author gaolong1
 * 
 * TODO 要更改此生成的类型注释的模板,请转至 窗口 - 首选项 - Java - 代码样式 -代码模板
 
*/

public class upload extends HttpServlet
{

    
/**
     * Destruction of the servlet. <br>
     
*/

    
private String uploadPath = "D:/upload/"// 用于存放上传文件的目录

    
private File tempPath = new File("D:/upload/tmp/"); // 用于存放临时文件的目录

    
public void destroy()
    
{
        
super.destroy(); // Just puts "destroy" string in log
        
// Put your code here
    }


    
/**
     * 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
     
*/

    
public void doPost(HttpServletRequest req, HttpServletResponse res)
            
throws ServletException, IOException
    
{
        res.setContentType(
"text/html; charset=GB2312");
        PrintWriter out 
= res.getWriter();
        System.out.println(req.getContentLength());
        System.out.println(req.getContentType());
        DiskFileItemFactory factory 
= new DiskFileItemFactory();
        
// maximum size that will be stored in memory
//         设置最多只允许在内存中存储的数据,单位:字节
//         设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
        factory.setSizeThreshold(4*1024);
        
// the location for saving data that is larger than getSizeThreshold()
        factory.setRepository(new File("d:/upload/addnetFile/temp"));

        ServletFileUpload upload 
= new ServletFileUpload(factory);
        
// maximum size before a FileUploadException will be thrown
//         设置允许用户上传文件大小,单位:字节
        
        
int maxUploadSize = 2*1024*1024;
        upload.setSizeMax(maxUploadSize);
        System.out.println(
"ww");
        
try
        
{
            List fileItems 
= upload.parseRequest(req);
            System.out.println(fileItems.size());
            System.out.println(fileItems.get(
0));
            
// assume we know there are two files. The first file is a small
            
// text file, the second is unknown and is written to a file on
            
// the server
            Iterator iter = fileItems.iterator();

            
// 正则匹配,过滤路径取文件名
            String regExp = ".+//(.+)$";

            
// 过滤掉的文件类型
            String[] errorType =
            
".exe"".com"".cgi"".asp" };
            Pattern p 
= Pattern.compile(regExp);
            
while (iter.hasNext())
            
{
                System.out.println(
"FileItem");
                FileItem item 
= (FileItem) iter.next();
                
// 忽略其他不是文件域的所有表单信息
                System.out.println("aaaaaaaaa");
                System.out.println(item.getContentType());
                System.out.println(
"aaaaaaaaa");
                
if (!item.isFormField())
                
{
                    System.out.println(
"bbbbbbbbbbb");
                    String name 
= item.getName();
                    
long size = item.getSize();
                    
if ((name == null || name.equals("")) && size == 0)
                        
continue;
                    
if(size > maxUploadSize)
                    
{
                        out.println(
"<script>alert('您上传的文件超过允许的大小,请重新上传此文件!')</script>");
                        
continue;
                    }

                    Matcher m 
= p.matcher(name);
                    
boolean result = m.find();
                    
if (result)
                    
{
                        
for (int temp = 0; temp < errorType.length; temp++)
                        
{
                            
if (m.group(1).endsWith(errorType[temp]))
                            
{
                                
throw new IOException(name + ": wrong type");
                            }

                        }

                        
try
                        
{
                            
                            Calendar calendar 
= Calendar.getInstance();
                            String year 
= new Integer( calendar.get(Calendar.YEAR)).toString();
                            String month 
= new Integer( calendar.get(Calendar.MONTH) + 1).toString();
                            String day 
= new Integer( calendar.get(Calendar.DATE)).toString();
                            String hour 
= new Integer( calendar.get(Calendar.HOUR_OF_DAY)).toString();
                            String minute 
= new Integer( calendar.get(Calendar.MINUTE)).toString();
                            String second 
= new Integer( calendar.get(Calendar.SECOND)).toString();

                            
// 保存上传的文件到指定的目录

                            
// 在下文中上传文件至数据库时,将对这里改写
                            
//不要直接用d:/这样跨平台不行,改成相对路径
                            
                            String uploadPath 
= "d:/" + year + "/" + month + "/" + day + "/";
                            String uploadFileName 
= year + month + day + hour + minute + second + m.group(1);
                            
                            File uploadDir 
= new File(uploadPath);
                            
                            
if(!uploadDir.exists())
                            
{
                                
if(uploadDir.mkdirs())
                                
{
                                    System.out.println(
"success");
                                }

                                
else
                                
{
                                    System.out.println(
"create dir faile");
                                }

                            }

                            
                            
                            
//File uploadFile = new File(uploadPath + uploadFileName);
                            
//uploadFile.createNewFile();
                            
                            
//item.write(new File("d:/" + m.group(1)));
                            
                            item.write(
new File(uploadPath + uploadFileName));
                            
                            System.out.println(uploadFileName 
+ "  " + size + "<br>");
                        }

                        
catch (Exception e)
                        
{
                            out.println(e);
                        }


                    }

                    
else
                    
{
                        
throw new IOException("fail to upload");
                    }

                }

            }

        }

        
catch (IOException e)
        
{
            out.println(e);
        }

        
catch (FileUploadException e)
        
{
            out.println(e);
        }


        
// 保存上传的文件到指定的目录

        
// 在下文中上传文件至数据库时,将对这里改写

    }


    
protected void doGet(HttpServletRequest request,
            HttpServletResponse response) 
throws ServletException, IOException
    
{
        
// TODO Auto-generated method stub
    }


    
/**
     * Initialization of the servlet. <br>
     * 
     * 
@throws ServletException
     *             if an error occure
     
*/

    
public void init() throws ServletException
    
{
        
// Put your code here
    }


}

 

html测试代码

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="multipart" content="form-data; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    
<form id="form1" name="form1" enctype="multipart/form-data" method="post" action="FileUpload">
        
<input id=aa name=file1 type="file"/>
        
<input id=bb name=file2 type="file"/>
        
<input type="submit" name="Submit" value="submit" />
    
</form>
</body>
</html>

这两段代码都能正确执行.

但我遇到一个怪问题,不知是tomcat的问题,还是哪的问题,这两段代码三个月前我写的时候能正确运行,昨天我重新试了半天,却不能运行了,也没报错,就是上传不了,今天,我什么都没改,却又能运行了,怪了,昨天我重起过tomcat,都不行.在我的编程经历中,遇到过好几次这样的情况,不知是怎么回事

补记:

用common-fileupload上传文件有个小地方一定要注意,即<input id=aa name=file1 type=file/>中的name一定要写,如果没写就会出现我上面的错误,上传不了文件,但却不报错.

原创粉丝点击