gpt4 book ai didi

java - NanoHttpd 保存上传的文件

转载 作者:行者123 更新时间:2023-11-30 02:54:12 24 4
gpt4 key购买 nike

我看了很多帖子,但找不到我的问题的答案......
所以我可以在我的设备上启动网络服务器,当我尝试上传文件时,浏览器显示“上传成功”,但我在我的设备上找不到该文件,我不知道它是否已上传到设备.我已经设置了所有权限并区分postget在我的 serve方法。

我想我必须从参数 Map<String, String> 中保存上传的文件文件。
我怎么能那样做?方法对吗?

这是我的代码 fragment :

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

}
}

最佳答案

我知道,这是一个很晚的回复,但我发布了答案以供将来引用。

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

关于java - NanoHttpd 保存上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23579848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com