问题
I have looked at many threads, but I can't find an answer to my question...
So I could start the webserver on my device, and when I try to upload a file the browser says "upload successfully", but I couldn't find the file on my device and I don't know whether it is uploaded to the device.
I have set all permissions and distinguish between post
and get
in my serve
method.
I think I have to save the uploaded files from the parameter Map<String, String>
files.
How could I do that? Is it the right way?
Here is my code snippet:
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:
I know, this is a very late response but I am posting the answer for future reference.
NanoHttpd automatically upload the file and saved in cache directory and return information (name,path etc) in files and params map. Write the following code in serve method.
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();
}
来源:https://stackoverflow.com/questions/23579848/nanohttpd-save-uploaded-files