解析混合表单请求的三种处理方法

Posted on 2007-01-22 13:33 blues 阅读(743) 评论(0)  编辑  收藏 所属分类: Web

包下载路径就不给了.自己随便google一下都可以找到

方法一:   commons-fileupload-1.1.1.jar开源包:

boolean isMultipart = org.apache.commons.fileupload.FileUploadBase
                .isMultipartContent(request);
       
        // Create a factory for disk-based file items
        if(isMultipart)
        {
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // 设置大文件的缓冲目录
            factory.setRepository(new File(this.getFilePathRepository()));
            // 设置内存缓冲大小
            factory.setSizeThreshold(this.getSizeThreshold());

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            // 设置文件的最大字节数
            upload.setSizeMax(this.getSizeMax());

            // 设置响应的字符编码
            httpServletResponse.setCharacterEncoding(this
                    .getResponseCharacterEncoding());

            this.getFileNames().clear();
            // Parse the request
            try
            {
                List items = upload.parseRequest(request);
                // Process the uploaded items
                for(Object itemT : items)
                {
                    FileItem item = (FileItem) itemT;
                    if(!item.isFormField())
                    {
                        // 文件名有可能包含路径
                        String name = item.getName();
                        if(name == null || name.length() < 1
                                || item.getSize() < 1)
                        {
                            continue;
                        }
                        try
                        {
                            // 去掉文件名的路径
                            name = (new File(name)).getName();
                            String path = this.getFilePathCurrent() + "/"
                                    + name;

                            item.write(new File(path));
                            this.fileNames.add(path);
                            request
                                    .setAttribute("msg",
                                            "save file successful!");
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                    else
                    {
                        //parameter
                        String par = item.getFieldName();
                        //value
                        System.out.println(par+"->"+item.getString());
                        //processUploadedFile(item);
                    }
                }
                if(request.getAttribute("msg") == null)
                {
                    request.setAttribute("msg", "save file failed!");
                    this
                            .receivingCompleted(false, request,
                                    httpServletResponse);
                }
                else
                {
                    this.receivingCompleted(true, request, httpServletResponse);
                }
            }
            catch (FileUploadException e)
            {
                e.printStackTrace();
                this.receivingCompleted(false, request, httpServletResponse);
            }
        }
        else
        {
            System.out.println("isMultipartContent = false");
            this.receivingCompleted(false, request, httpServletResponse);
        }

方法二:  oreilly开源包

String projectName = null, fileName = null,dirName="E:/upload";
        try
        {
            // Use an advanced form of the constructor that specifies a
            // character
            // encoding of the request (not of the file contents) and a file
            // rename policy.
            MultipartRequest multi = new MultipartRequest(request, dirName,
                    10 * 1024 * 1024, "ISO-8859-1",
                    new DefaultFileRenamePolicy());

            projectName = multi.getParameter("projectName");
            System.out.println("projectName = " + projectName);

            Enumeration params = multi.getParameterNames();
            while (params.hasMoreElements())
            {
                String name = (String) params.nextElement();
                String value = multi.getParameter(name);
                if(name == "projectName")
                    projectName = value;
                System.out.println(name + "=" + value);
            }
            System.out.println();

            System.out.println("FILES:");
            Enumeration files = multi.getFileNames();
            while (files.hasMoreElements())
            {
                String name = (String) files.nextElement();
                String filename = multi.getFilesystemName(name);
                String originalFilename = multi.getOriginalFileName(name);
                String type = multi.getContentType(name);
                File f = multi.getFile(name);
                System.out.println("name: " + name);
                System.out.println("filename: " + filename);
                System.out.println("originalFilename: " + originalFilename);
                System.out.println("type: " + type);
                if(f != null)
                {
                    System.out.println("f.toString(): " + f.toString());
                    System.out.println("f.getName(): " + f.getName());
                    fileName = f.getName();
                    System.out.println("f.exists(): " + f.exists());
                    System.out.println("f.length(): " + f.length());
                }
                System.out.println();
            }

//            ArrayList<Project> projects = (ArrayList<Project>) session
//                    .getAttribute("projects");
//            System.out.println("projectName, fileName = " + projectName + ", "
//                    + fileName);
//            Project p = new Project(projectName, fileName);
//            System.out.println("PROJ = " + p);
//            projects.add(p);

        }
        catch (IOException lEx)
        {
            lEx.printStackTrace();
        }


方法三:  jspsmartupload.jar开源包

selectfile.jsp---->web.xml >servletUpload.java  基本就是这么个结构

下面是代码:

//selectfile.jsp

<%@ page contentType="text/html;charset=GBK" %>

<html>
<head>
 <title>file upload</title>
</head>

<body>
<font size="5" color="#FF0000">
   <b>文件上传 - 使用jspsmart upload组件</b>
</font><br>

<form name="selectfile" enctype="multipart/form-data" method="post" action="servletUpload">
 <p>文件名称:
 <input type="file" name="ulfile" size="20" maxlength="80"><br>
 </p>
  <p>上传路径:
 <input type="text" name="PATH" size="30" maxlength="50"><br>
 </p>
 <p>附加内容:
 <input type="text" name="other" size="30" maxlength="50"><br>
 </p>
 <p>
 <input type="submit" value="上传">
 <input type="reset" value="清除">
 </p>
</form>

</body>
</html>

//servletUpload.java 

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.jspsmart.upload.*;

public class servletUpload extends HttpServlet {
 
 private ServletConfig config;
 /**
 * 初始化Servlet
 */
 final public void init(ServletConfig config) throws ServletException {
  this.config = config;
 }
 
 /**
 * 处理GET请求
 */
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  PrintWriter out = response.getWriter();
  out.println("<HTML>");
  out.println("<BODY BGCOLOR='white'>");
  out.println("<H1>jspSmartUpload : Servlet Sample</H1>");
  out.println("<HR><BR>");
  out.println("The method of the HTML form must be POST.");
  out.println("</BODY>");
  out.println("</HTML>");
 }
 
 /**
 * 响应POST请求
 */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
  PrintWriter out = response.getWriter();
  out.println("<HTML>");
  out.println("<BODY BGCOLOR='white'>");
  out.println("<H1>jspSmartUpload : Servlet Sample</H1>");
  out.println("<HR>");

  // 变量定义
  int count=0;
  SmartUpload mySmartUpload = new SmartUpload();

  try {
   // 初始化
   mySmartUpload.initialize(config,request,response);

   // 上载
   mySmartUpload.upload();
   com.jspsmart.upload.File f1 = mySmartUpload.getFiles().getFile(0);
   String name = f1.getFileName();
  // System.out.println (name);
 
  

   // 保存上载文件到指定目录
   // PATH为form表单提交过来的
   count = mySmartUpload.save(mySmartUpload.getRequest().getParameter("PATH"));
   //other为form表单提交过来的
   String other=mySmartUpload.getRequest().getParameter("other"); //这里可以对other进行处理
   //request.getParameter("PATH");request.gerParameter("other");
  
   // 显示处理结果
   out.println(count + " file uploaded.");

  } catch (Exception e){
   out.println("Unable to upload the file.<br>");
   out.println("Error : " + e.toString());
  }
 
  out.println("</BODY>");
  out.println("</HTML>");
    }
}


//web.xml的配置如下:


<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>


  <servlet>
    <servlet-name>upload</servlet-name>
    <servlet-class>servletUpload</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>upload</servlet-name>
    <url-pattern>servletUpload</url-pattern>
  </servlet-mapping>


  <welcome-file-list>
    <welcome-file>selectfile.jsp</welcome-file>
  </welcome-file-list>


</web-app>

需要在WEB-INF\lib中引入jspsmart这个包,上网找一下就有,很多都有的下 www.jspsmart.com 这里是他的官方网站.把编译后的class文件放到WEB-INF\classes下就可以运行了.

这里面用到了jspsmart提供的mySmartUpload.getRequest().getParameter("other"); 这个东西,由于开始的时候觉得PATH地址没有必要传递就早早的把这条代码删掉了,后来就想用request.getParameter("")这个得到信息,可是总是出错.在网上找了N多文章,很多人面临同样的困难.于是想用逻辑关系把这种情况避免掉.就是用单独的form上传用另一个form往数据库里录入.可是录入的时候又得不到要上传的文件名,我是想把文件名存到数据库里的.如果一定要得的话就得放到session里去,一想这样太麻烦,弄不好还容易出bug,要是把临时信息放到数据库里去,有多人一起操作的话又是个问题,其中还遇到了想往file的属性value里写信息的问题.只能读,不能写,就是这个结果.每次都是快成功的时候就卡在这样的小地方了.于是上网查找其他组件看看能不能有相应的功能.这时候使用了fileupload这个组件,网友使用的情况来看这个也要好于jspsmart可是同样没找到getParameter这样的方法.

于是继续在网上搜,结果找到自己原来用的那段代码,发现...原来mySmartUpload.getRequest().getParameter就可以实现了.巨汗啊.现在改成这个样子,可以运行了.不过也许后面还要改成其他的组件,使上传的数据更稳定一些.现在就先这样了,商务逻辑已经实现了


//      变量定义
        /*int count=0;
        SmartUpload mySmartUpload = new SmartUpload();


        try {
         // 初始化
         mySmartUpload.initialize(config,request,response);

         mySmartUpload.setAllowedFilesList("doc,txt");
         mySmartUpload.setDeniedFilesList("exe,bat,jsp,htm,html,xml,");
         // 上载
         mySmartUpload.upload();
         com.jspsmart.upload.File f1 = mySmartUpload.getFiles().getFile(0);
        

         // 保存上载文件到指定目录
         // PATH为form表单提交过来的
         count = mySmartUpload.save("e:/current2");


         //other为form表单提交过来的
         String other=mySmartUpload.getRequest().getParameter("other"); //这里可以对other进行处理
         //request.getParameter("PATH");request.gerParameter("other");
        
         // 显示处理结果
         System.out.println(count + " file uploaded.");

        } catch (Exception e){
         System.out.println("Unable to upload the file.<br>");
         System.out.println("Error : " + e.toString());
        }


        com.jspsmart.upload.Request re = mySmartUpload.getRequest();
        Enumeration params = re.getParameterNames();
        while (params.hasMoreElements())
        {
            String name = (String) params.nextElement();
            String value = re.getParameter(name);
           
            System.out.println(name + "=->" + value);
        }
        System.out.println("end2");*/


只有注册用户登录后才能发表评论。


网站导航: