Retrieve file from POST request with NanoHttpd

假如想象 提交于 2019-12-13 02:54:55

问题


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
    }

    ...

}

回答1:


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 ");
}


来源:https://stackoverflow.com/questions/27624936/retrieve-file-from-post-request-with-nanohttpd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!