1

我正在尝试使用 NanoHttpd 库通过表单中的 POST 请求将文件上传到我的 Android 服务器。我确实在服务器端收到了 POST 请求。我的问题是如何从 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
    }

    ...

}
4

1 回答 1

6

昨晚我找到了解决方案,上传文件很容易......

首先,您管理“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 ");
}
于 2014-12-25T07:35:01.957 回答