Search code examples
androidnanohttpd

Uploading file to nanoHttpd server Android


How can I retrieve POST parameters in NanoHttpd Serve method. This is my html form bellow

<form  name="a" enctype="multipart/form-data\  method="post" >"
     <input type="file" name"file" multiple/>"+
     <input type="hidden" name="extradata" value="test"/>
     <input type="submit" value="upload" >
</form>

Im not able to get even the content length for file being submitted thru the form

  public Response serve(IHTTPSession session) {
        Map<String, String> params = session.getParms();                           
        Map<String, String> files = new HashMap<String, String>();
        if (Method.POST.equals(session.getMethod()) || Method.PUT.equals(session.getMethod())) {
            try {
                session.parseBody(files);    
                StringBuilder builder = new StringBuilder();    
                builder.append("| conLen  " + (session.getHeaders().get("content-length")) + "| \n");    
                Set keys = files.keySet();
                for (Object key : keys) {
                    builder.append(" key: " + key + " value: " + files.get(key) + "\n");
                }
                return new Response(builder.toString());
            } catch (Exception ex) {
                Log.d("server", ex.toString());
            }

        }

}

}

And response from this code is:

conLen null key: postData value: ------WebKitFormBoundaryt5gZYrmlLiPVa6aM Content-Disposition: form-data; name="extradata" test ------WebKitFormBoundaryt5gZYrmlLiPVa6aM--


Solution

  •        if (Method.POST.equals(session.getMethod()) || Method.PUT.equals(session.getMethod())) {
                Log.d("server","inside receive file!");
                try{session.parseBody(files);}catch (Exception e){Log.d("server","error on parseBody" +e.toString());}
    
    
                File file = new File(files.get("uploadFile"));
    }
    

    Actually the problem was with NanoHTTPD server. I changed to 2.1.1 version and now is working as it should be. With the code above I'm able to get the uploaded file.