在Servlet中获取表单值

时间:2014-02-09 16:11:24

标签: java jquery html ajax servlets

我是servlet的新手。我尝试做的是使用servlet将文件上传到我的服务器,并发送一个文本值,即文件名在服务器端进行更改。问题是我使用ajax post将表单数据提交给servlet但是在我的servlet中,我从request.getParameter获取了null值。

这是我的HTML;

$("#fileUp").html(  "<form enctype='multipart/form-data' id='uploadForm' action='" + url + "/PrjHRService/FileUpload'>"+
                        "<input name='file' id='file' type='file' size='50'>"+
                        "<input name='fname' type='text' >"+
                        "<input id='btnUpload' value='Upload' type='submit'>"+
                        //"<div id='imgLink'></div>"+
                        "</form>" );

这是我对服务器的jquery ajax调用;

$("#uploadForm").submit(function() {            
            var formData = new FormData($(this)[0]);
            $.ajax({
                   type: "POST",
                   url: $("#uploadForm").attr("action"),
                   data: formData, 
                   async: false,
                   success: function(data)
                   {
                       if(data.res === "true"){
                         jsi.showMsg("Uploaded Successfully");
                         $("#imgLink").html("Uploaded Successfully");
                       }else{
                         jsi.showMsg("Error Uploading");    
                       }
                   },
                   contentType: false,
                   processData: false
                 });

            return false; // avoid to execute the actual submit of the form.
        });

这是我从servlet中获取表单值的方法;在那里你会看到一行String fileExt = request.getParameter(&#34; fname&#34;);我发现fileExt为null,这是我的问题。

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("application/json");
      String fileExt=request.getParameter("fname");
      java.io.PrintWriter out = response.getWriter( );
      if( !isMultipart ){

         JSONObject o=new JSONObject();
          try {
            o.put("res", "false");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          out.println(o.toString());

         return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();
      while ( i.hasNext () ) 
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )  
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            //String[] parts = fileName.split(".");
            //fileName = parts[0] + "." + parts[1];
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath + 
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath + 
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            JSONObject o=new JSONObject();
            o.put("res", "true");
            //out.println("Uploaded Filename: " + fileName + "<br>");
            out.println(o.toString());
            //out.println("Uploaded Successfully");
         }
      }
     /* out.println("</body>");
      out.println("</html>");*/
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }

1 个答案:

答案 0 :(得分:2)

如果您要上传文件,<form/>的{​​{1}}必须设置为method。然后,在服务器端,您需要从请求中获取输入流并读取数据---您需要在POST方法(http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29)中执行此操作。当然有很多图书馆,你这样做,例如那些来自阿帕奇的人。

您必须记住,使用doPostPOST所有表单的参数添加到POST正文中,与enctype="multipart/from-data"的区别在于参数连接到请求的区别URL(如所谓的QUERY_STRING)。方法enctype="application/x-www-form-urlencoded"仅适用于通过URL发送的参数。因此,在您的情况下,您需要读取POST数据,解析它并找出getParameter的值。 POST可能如下所示:

fname

如果您手动将一些参数添加到-----------------------------8022333619518 Content-Disposition: form-data; name="fname" myfilename.txt -----------------------------8022333619518 Content-Disposition: form-data; name="submit" Send -----------------------------8022333619518-- 网址,action方法会找到它。

由于您没有上传任何文件(不是吗?),您可以将getParameter设置为使用enctype="application/x-www-form-urlencoded",因为它会将所有表单的输入添加到URL。但是您的代码建议您稍后上传文件,因此它不适用于文件内容。

当您使用Apache的getParameter时,您可以看到parseParameterMap方法,获取地图,然后获取ServletFileUpload参数(它应该是列表中的第一个元素)为{{1并使用fname获取其内容。它应该是你要找的东西:

FileItem