1

I am trying to use the NanoHttpd library to upload files to my Android server by using a POST request from a form. I do receive the POST request on the server side. My question is how to retrieve the file from the POST request so I can save it somewhere in the device memory.

the form :

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

the serve method :

@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
    }

    ...

}
zxzak
  • 8,985
  • 4
  • 27
  • 25

1 Answers1

6

Last night i found solution it's very easy to upload file....

First you have manage 'TempFileManager'. It's handle temp file directory so it' create file and delete automatically after your work finish like copy,read,edit,move etc...

   server.setTempFileManagerFactory(new ExampleManagerFactory());

So now you not have manage temp file it's work automatically...

Manage post request like this

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 ");
}
pathik devani
  • 530
  • 5
  • 13
  • 2
    By adapting this code to my solution I was able to save the file in the internal memory, just as I wanted. Additionally, I was able to retrieve the original filename from the session.getParams() hashmap by using the same key. – zxzak Dec 27 '14 at 11:22
  • Thanks, your solution also worked for me. I had problem in uploading large zip file. The problem I faced occured while the whole file sent to the server end by NanoHTTPd server, it clears the file while it was still being processing. Therefore, making a custom FileManager worked for me. To be more specific, I referred the following code to create the custom file manager: https://github.com/NanoHttpd/nanohttpd/blob/master/samples/src/main/java/org/nanohttpd/samples/tempfiles/TempFilesServer.java – muzamil Jan 19 '22 at 06:00