csdn产品小助手 2014-02-09 16:11 采纳率: 0%
浏览 95

在Servlet中获取表单值

I am new to servlet. What I'm trying to do is upload the file to my server using servlet alongside I send one text value which is file name to change in server side. The problem is I submit the form data to servlet using ajax post but in my servlet, I'm getting null value from request.getParameter.

This is my 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>" );

This is my jquery ajax call to server;

$("#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.
        });

This is how I get the value from form in my servlet; In there you will see the line String fileExt=request.getParameter("fname"); I found out that fileExt is null which is my problem.

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条回答 默认 最新

  • weixin_33720186 2014-02-09 16:15
    关注

    If you want to upload file, <form/>'s method must be set to POST. Then, at the server side, you need to get input stream from the request and read data --- and you need to do that in doPost method (http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29). Of course there are many libraries, that do that from you, e.g. those from apache.

    You must remember, that using POST with enctype="multipart/from-data" adds all form's parameters to POST body, what is distinctive from enctype="application/x-www-form-urlencoded" where parameters are concatenated to request URL (as so called QUERY_STRING). Method getParameter works only on parameters sent via URL. So in your case you need to read POST data, parse it and find out the value of fname. POST that might look like this:

    -----------------------------8022333619518
    Content-Disposition: form-data; name="fname"
    
    myfilename.txt
    -----------------------------8022333619518
    Content-Disposition: form-data; name="submit"
    
    Send
    -----------------------------8022333619518--
    

    If you add manually some parameters to action URL, getParameter method will find it.

    And as you do not upload any file (aren't you?) you can set enctype="application/x-www-form-urlencoded" to use getParameter, as it adds all form's inputs to URL. But your code suggests, that you will upload a file later, so it won't work for the file content.

    As you use ServletFileUpload from Apache, you can see parseParameterMap method, get the map, then get fname parameter (it should be first element on the list) as FileItem and get its content with getString. It should be what you are looking for:

    Map<String, List<FileItem>> map = ServletFileUpload.parseParameterMap(request);
    List<FileItem> list = map.get("fname");
    if (list != null && list.size() >= 1) {
        FileItem item = list.get(0);
        System.out.println("And the winner is... " + item.getString);
    }
    else {
        System.out.println("Dammit! Still no luck!");
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘