2015-10-19 22 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

是的,我只是添加了這三行,它的工作原理是這樣的:在我的成功函數,它似乎從來沒有進入那裏 –