1

我查看了很多线程,但找不到问题的答案......
所以我可以在我的设备上启动网络服务器,当我尝试上传文件时,浏览器显示“上传成功”,但我不能'在我的设备上找不到文件,我不知道它是否已上传到设备。我已经设置了所有权限并在我的方法中区分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);

    }
}
4

1 回答 1

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

实用程序.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();
}
于 2015-02-03T21:09:58.783 回答