2014-12-23 34 views
0

我正嘗試使用NanoHttpd庫通過使用來自表單的POST請求將文件上傳到我的Android服務器。我確實收到服務器端的POST請求。我的問題是如何從POST請求中檢索文件,以便將其保存在設備內存的某個位置。使用NanoHttpd從POST請求中檢索文件

形式:

<form action='?' method='post' enctype='multipart/form-data'> 
    <input type='file' name='file' />`enter code here` 
    <input type='submit'name='submit' value='Upload'/> 
</form> 

發球方法:

@Override 
public Response serve (IHTTPSession session) { 
Method method = session.getMethod(); 
String uri = session.getUri(); 

    if (Method.POST.equals(method)) { 
     //get file from POST and save it in the device memory 
    } 

    ... 

} 

回答

2

昨晚我找到的解決方案是很容易上傳文件....

首先,你必須管理「TempFileManager 」。它的手柄臨時文件目錄,以便它創建的文件和你的工作完成後自動刪除比如複製,讀取,修改,移動等..

server.setTempFileManagerFactory(new ExampleManagerFactory()); 

所以,現在你沒有管理臨時文件,它會自動的工作...

管理崗位要求這樣

private Response POST(IHTTPSession) { 

    try { 
     Map<String, String> files = new HashMap<String, String>(); 
     session.parseBody(files); 

     Set<String> keys = files.keySet(); 
     for(String key: keys){ 
      String name = key; 
      String loaction = files.get(key); 

      File tempfile = new File(loaction); 
      Files.copy(tempfile.toPath(), new File("destinamtio_path"+name).toPath(), StandardCopyOption.REPLACE_EXISTING); 
     } 


    } catch (IOException | ResponseException e) { 
     System.out.println("i am error file upload post "); 
     e.printStackTrace(); 
    } 

    return createResponse(Status.OK, NanoHTTPD.MIME_PLAINTEXT, "ok i am "); 
} 
+2

通過適應這個代碼到我的解決方案,我能夠將文件保存在內存中,只是因爲我想。此外,我能夠通過使用相同的密鑰從session.getParams()hashmap中檢索原始文件名。 – zxzak