套用的别人的模版,可是我这总抛io.exception,上传失败,
请各位帮帮忙,看一下这个程序。感激不尽!你们应该清楚。
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 org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;/*
 * 创建日期 2005-4-10
 *
 * TODO 要更改此生成的文件的模板,请转至
 * 窗口 - 首选项 - Java - 代码样式 - 代码模板
 *//**
 * @author gaolong1
 *
 * TODO 要更改此生成的类型注释的模板,请转至
 * 窗口 - 首选项 - Java - 代码样式 - 代码模板
 */
public class FileUpload extends HttpServlet { /**
  * Destruction of the servlet. <br>
  */
 private String uploadPath = "D:\\addnetFile\\"; // 用于存放上传文件的目录
    private File tempPath =new File("D:\\addnetFile\\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
        factory.setSizeThreshold(4096);
        // the location for saving data that is larger than getSizeThreshold()
        factory.setRepository(new File("d:\\File\\addnetFile\\temp"));        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum size before a FileUploadException will be thrown
        upload.setSizeMax(1000000);
        try{
        List fileItems = upload.parseRequest(req);
        // 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()) {
         FileItem item = (FileItem)iter.next();
         //忽略其他不是文件域的所有表单信息
         if (!item.isFormField()) {
             String name = item.getName();
             long size = item.getSize();
             if((name==null||name.equals("")) && size==0)
                 continue;
          Matcher m = p.matcher(name);
         boolean result = m.find();  ---》 result 为FALSE,为什么?[/color]
         if (result){
             for (int temp=0;temp<errorType.length;temp++){
             if (m.group(1).endsWith(errorType[temp])){
                   throw new IOException(name+": wrong type");
             }
             }
             try{//        保存上传的文件到指定的目录//        在下文中上传文件至数据库时,将对这里改写
                     item.write(new File("d:\\" + m.group(1)));                   out.print(name+"&nbsp;&nbsp;"+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);
         }//  保存上传的文件到指定的目录//  在下文中上传文件至数据库时,将对这里改写    }
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occure
  */
 public void init() throws ServletException {
  // Put your code here
 }}

解决方案 »

  1.   

    这里就是不执行判断语句,result为false;所以那个 throw new IOException("fail to upload"); 
    直接抛上去了。结果就是java.io.ioexception: fail to upload
      

  2.   

    上传文件为什么不用blob字段,很方便的,性能也很不错。
      

  3.   

    我觉得应该是String name = item.getName()或者正则表达式的问题
    这里得到的name是带全路径的文件名么?你的正则只能匹配全路径的情况。而且只支持windows文件格式。
    如果不是全路径的文件名,或者非windows文件格式的,当然只能返回false了。你可以改一下正则表达式,或者换另外的方法获得文件名。
      

  4.   

    正则表达式有问题
    就匹配了一个 \ 后面跟任何东西都可以
    路径中没有 \ 或者 \ 后没有任何东西  
    就false了 
      

  5.   

    如果想拿到文件名和文件类型的话,可以用如下方法:String fileName = path.substring(path.lastIndexOf('/'));
    String fileType = fileName.substring(
    fileName.lastIndexOf('.') + 1).toLowerCase();//得到.后面的文件扩展名
      

  6.   

    既然只有文件名,那就用8楼的第二句代码就OK了。
    String fileType = fileName.substring(
                            fileName.lastIndexOf('.') + 1).toLowerCase();