NanoHttpd保存上传的文件

时间:2014-05-10 10:22:15

标签: java android upload webserver nanohttpd

我看过许多帖子,但我无法找到答案... ... 所以我可以在我的设备上启动网络服务器,当我尝试上传文件时,浏览器会说“#34;成功上传"”但是我无法在设备上找到该文件而我没有知道它是否上传到设备。 我已设置所有权限,并在post方法中区分getserve

我想我必须从参数Map<String, String>文件中保存上传的文件 我怎么能这样做?这是正确的方式吗?

这是我的代码段:

private class MyHTTPD extends NanoHTTPD {

    public MyHTTPD() throws IOException {
        super(PORT);
    }
    public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) {           
        if (method.equals(Method.GET)) {
            return get(uri, method, headers, parms, files);
        }
        return post(uri, method, headers, parms, files);
    }

    public Response get(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) {
        String get = "<html><body><form name='up' method='post' enctype='multipart/form-data'>"
                + "<input type='file' name='file' /><br /><input type='submit'name='submit' "
                + "value='Upload'/></form></body></html>";
        return new Response(get);
    }

    public Response post(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) {
        String post = "<html><body>Upload successfull</body></html>";
        return new Response(post);

    }
}

1 个答案:

答案 0 :(得分:1)

我知道,这是一个非常晚的回复,但我发布的答案供将来参考。

NanoHttpd自动上传文件并保存在缓存目录中并返回文件和参数图中的信息(名称,路径等)。在serve方法中写下以下代码。

File dst = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() +"/"+ parameters.get("myfile"));
File src = new File(files.get("myfile"));
try {
      Utils.copy(src, dst);
}catch (Exception e){ e.printStackTrace();}

Utils.copy

public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}
相关问题