2014-12-23 27 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