2014-05-10 114 views
1

我已經看過很多主題,但我找不到我的問題的答案...
因此,我可以啓動我的設備上的網絡服務器,當我嘗試上傳文件的瀏覽器說「成功上傳」,但我無法找到我的設備上的文件,我不知道它是否上傳到設備。 我已經設置了所有權限,並在我的serve方法中區分了postgetNanoHttpd保存上傳的文件

我想我必須保存從參數Map<String, String>文件上傳的文件。
我該怎麼做?這是正確的方式嗎?

這裏是我的代碼片段:

private class MyHTTPD extends NanoHTTPD { 

    public MyHTTPD() throws IOException { 
     super(PORT); 
    } 
    public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) {   
     if (method.equals(Method.GET)) { 
      return get(uri, method, headers, parms, files); 
     } 
     return post(uri, method, headers, parms, files); 
    } 

    public Response get(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { 
     String get = "<html><body><form name='up' method='post' enctype='multipart/form-data'>" 
       + "<input type='file' name='file' /><br /><input type='submit'name='submit' " 
       + "value='Upload'/></form></body></html>"; 
     return new Response(get); 
    } 

    public Response post(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { 
     String post = "<html><body>Upload successfull</body></html>"; 
     return new Response(post); 

    } 
} 

回答

1

我知道,這是一個非常晚迴應,但我張貼以供將來參考答案。

NanoHttpd自動上傳文件並保存在緩存目錄中,並返回文件和參數圖中的信息(名稱,路徑等)。在服務方法中編寫以下代碼。

File dst = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() +"/"+ parameters.get("myfile")); 
File src = new File(files.get("myfile")); 
try { 
     Utils.copy(src, dst); 
}catch (Exception e){ e.printStackTrace();} 

Utils.copy

public static void copy(File src, File dst) throws IOException { 
    InputStream in = new FileInputStream(src); 
    OutputStream out = new FileOutputStream(dst); 

    // Transfer bytes from in to out 
    byte[] buf = new byte[1024]; 
    int len; 
    while ((len = in.read(buf)) > 0) { 
     out.write(buf, 0, len); 
    } 
    in.close(); 
    out.close(); 
} 
+0

我們應該刪除臨時文件?或者NanoHttpd在響應結束時刪除它? –

+0

NanoHttpd應刪除緩存文件。如果不是系統會的話。不要擔心。 – shantanu

+0

你能說說你在哪裏找到「緩存」目錄嗎?我的班級路徑中沒有任何環境類... – Matthieu