2009-11-25 55 views
2

我希望能夠讓用戶將短音頻樣本上傳到我的應用程序引擎應用程序,並將它們存儲在提供的數據存儲區中。我正在使用Java servlet版本。用java servlet將文件上傳到應用程序引擎

我的問題是使用多部分表單來上傳文件。使用正常的request.getParameter()方法返回null與多部分表單。我已閱讀了使用oriely MultiPartForm類,但似乎涉及將文件保存到服務器文件系統,這是不可能的。

有人可以告訴我如何上傳文件,以便它在AppEngine數據庫Blob對象中結束?

謝謝

回答

3

你可以這樣來做:例如

<input id="file-pdf" type="file" name="file-pdf"> 
<button id="submit-pdf">submit</button> 

的JavaScript

$("#submit-pdf").click(function() { 
    var inputFileImage = document.getElementById("file-pdf"); 
    var file = inputFileImage.files[0]; 
    var data = new FormData(); 
    data.append("file-pdf",file); 
    $.ajax({ 
    url: "uploadpdf", 
    type: 'POST', 
    cache : false, 
    data : data, 
    processData : false, 
    contentType : false, 
    dataType: "json",  
    success: function (response) {   
     if(response.success){ 
      console.log("ok"); 
     }else{ 
      console.log("fail"); 
     } 

    } 
});  
}); 

和servlet

public void doPost(HttpServletRequest req, HttpServletResponse resp) 
    throws IOException { 
    JSONObject finalJson = new JSONObject(); 
    Boolean success = false; 
    String ajaxUpdateResult = ""; 
    try { 
      ServletFileUpload upload = new ServletFileUpload(); 
      FileItemIterator iterator = upload.getItemIterator(req); 
      while (iterator.hasNext()) { 
      FileItemStream item = iterator.next(); 
      InputStream stream = item.openStream(); 
      if (item.isFormField()) { 
       logger.warning("Got a form field: " + item.getFieldName()+ "value="+ item.getName()); 
       String idForm= item.getFieldName(); 
      } else { 
       logger.warning("Got an uploaded file: " + item.getFieldName() + 
          ", name = " + item.getName()+ " content="+item.getContentType() + " header="+item.getHeaders()); 
       // here save 
       //success = insertFile(String title,String mimeType, String filename, InputStream stream);     

      } 
      } 
    } catch (Exception ex) { 

    } 

    finalJson.put("success", success); 
    resp.setCharacterEncoding("utf8"); 
    resp.setContentType("application/json"); 
    PrintWriter out = resp.getWriter(); 
    out.print(finalJson);   
} 
相關問題