2015-10-19 45 views
1

我在项目中遇到了一些问题。 您好几个jsp和Java类。在一个jsp中,我创建一个只有输入type =“file”和type =“submit”的表单,然后我有一个ajax调用,并将所有formdata发送到我的servel上的doPost类。然后我将该文件发送到数据库,这一切都很好,我的问题是我想从数据库中返回id到.jsp。我可以访问并在doPost上打印以检查我的密钥,但无法将它发送到ajax调用中的成功函数。 这里是我的代码,我非常赞赏任何形式的帮助,谢谢!上传多个数据文件时,在ajax调用时从servel获得响应

<form id="uploadDocuments" target="invisible" method="POST" action="UploadDocumentsAjaxService" enctype="multipart/form-data"> 
        <iframe name="invisible" style="display:none;"></iframe>      
        <h3 style="width: 71%;margin-left: 8%;">ANEXAR FICHEIROS:</h3> 
        <h4 style="margin-left: 8%; color: #F7A707" >Escolher ficheiro para anexar: </h4> 
        <input type="file" id="file_input" name="file" size="50" style="width: 60%; margin-left: 8%;"/> 
        <input type="submit" value="Upload" /> 
       </form> 

的我有我的AJAX调用:

$("#uploadDocuments").submit(function (e) { 
     alert(10); 
     alert($("#uploadDocuments").attr('action')); 
     $.ajax({ 
      type: $("#uploadDocuments").attr('method'), 
      url: $("#uploadDocuments").attr('action'), 
      contentType: $("#uploadDocuments").attr("enctype"), 
      data: new FormData($("#uploadDocuments")[0]), 
      processData: true, 
      success: function (data) { 
       alert("submitDocument"); 
       alert(); 
       /* key = data; 
       addFilesToTable(key); */ 
       return true; 
      } 
     }); 
     e.preventDefault(); 
     $(form).off('submit'); 
     return false; 
     }); 

然后我的servlet类:

protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ 
    response.setContentType("text/html;charset=ISO-8859-1"); 

    PrintWriter out = response.getWriter(); 

    boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
    ChangeEntityRequestActionBean actionBean = new ChangeEntityRequestActionBean(); 

    if(!isMultipart) 
     return; 

    // Create a factory for disk-based file items 
    DiskFileItemFactory factory = new DiskFileItemFactory(); 

    // Sets the size threshold beyond which files are written directly to 
    // disk. 
    factory.setSizeThreshold(MAX_MEMORY_SIZE); 

    // constructs the folder where uploaded file will be stored 
    String uploadFolder = getServletContext().getRealPath("") + DATA_DIRECTORY; 

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

    // Set overall request size constraint 
    upload.setSizeMax(MAX_REQUEST_SIZE); 
    String fileName = ""; 
    Long documentKey = null; 
    String key = ""; 

    try { 
     // Parse the request 
     List items = upload.parseRequest(request); 
     Iterator iter = items.iterator(); 
     while (iter.hasNext()) { 
      FileItem item = (FileItem) iter.next(); 

      if (!item.isFormField()) { 
       fileName = new File(item.getName()).getName(); 
       String filePath = uploadFolder + File.separator + fileName; 
       File uploadedFile = new File(filePath); 
       System.out.println(filePath); 
       // saves the file to upload directory 
       item.write(uploadedFile); 
      } 
      documentKey = actionBean.insertDocument(item, fileName); 

      System.out.println("Key from DAO ------->>>>>"+documentKey); 
      key = String.valueOf(documentKey); 

     } 

     System.out.println("Key in String from DAO ----->"+key); 
     System.out.println(); 

     out.println("success"); 
     response.flushBuffer(); 
    }catch (FileUploadException ex) { 
     throw new ServletException(ex); 
    } catch (Exception ex) { 
     throw new ServletException(ex); 
    } finally { 
     out.close(); 
    } 


} 

所有我想要的是送把键值改为通过out.println这样我就可以在jquery函数上使用该值

+0

发送它为JSON哥们。 – r3wt

+0

我该怎么做? :/ –

+0

我试图用json发送密钥,它不起作用 –

回答

0

在您的servlet中的doPost()的第一行中,更改该conte对“application/json”的响应的nt类型。然后将JSON字符串写入输出流。有libraries可以为你做这件事,但对于这么简单的事情,你可以自己编写JSON。这可能实际上有优势,因为您的密钥是java long;把它当作一个字符串,你不必担心整数是如何表示的。

// replace out.println("success"); with this: 
out.print("{\"key\": \"" + key + "\"}"); 

然后在成功的回调函数,你可以访问密钥作为data对象的字段。您需要在ajax方法中指定数据类型(dataType: 'json')。

success: function (data) { 
    var key = data['key']; 
    addFilesToTable(key); 
    return true; 
} 
+0

它有一点帮助,谢谢! )。但现在它发送字符串{\“key \”:\“”+ key +“\”}“为一个文件和IE询问我是否要打开或保存...我无法获得警报 –

+0

嗯,我不知道为什么会发生,看你的代码。缓存:假的, \t \t \t的contentType:假的, \t \t \t过程数据:假的, – Tap

+0

是的,我只是添加了这三行,它的工作原理是这样的:在我的成功函数,它似乎从来没有进入那里 –