1
Я новичок NanoHTTPD, я изучил документы NanoHttpd save uploaded files и https://github.com/romsahel/simplewebserverКак я могу изменить код для загрузки нескольких файлов с помощью NanoHTTPD в Android?
Следующий код можно загрузить один файл андроид мобильный телефон с помощью Wi-Fi.
Теперь я надеюсь загрузить несколько файлов на мобильный телефон Android, как я могу изменить следующий код, чтобы сделать это? Благодаря!
package com.wade.webserver;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyServer extends NanoHTTPD {
private final static int PORT = 8189;
private String rootDir = null;
@SuppressWarnings("serial")
public static final List<String> INDEX_FILE_NAMES = new ArrayList<String>() {
{
add("index.html");
add("index.htm");
}
};
public MyServer() throws IOException {
super(PORT);
File f;
f = new File("/storage/sdcard0/www");
if (f.canWrite()) {
rootDir = "/storage/sdcard0/www";
System.out.println("rootDir = " + rootDir);
}
else {
f = new File("/storage/sdcard1/www");
if (f.canWrite()) {
rootDir = "/storage/sdcard1/www";
System.out.println("rootDir = " + rootDir);
}
else {
rootDir = "/storage/sdcard0";
System.out.println("set rootDir default " + rootDir);
}
}
start(NanoHTTPD.SOCKET_READ_TIMEOUT);
}
@Override
public Response serve(IHTTPSession session)
{
Map<String, String> header = session.getHeaders();
Map<String, String> parms = session.getParms();
Method method = session.getMethod();
String uri = session.getUri();
System.out.println(method + " '" + uri + "' ");
if (Method.POST.equals(method) || Method.PUT.equals(method))
handlePost(session, parms);
File file = new File(rootDir + uri);
if (!file.exists()) {
return getNotFoundResponse();
}
if (file.isDirectory())
return listDirectory(file, header, uri);
else
return downloadFile(file);
}
private Response handlePost(IHTTPSession session, Map<String, String> parms)
{
Map<String, String> files = new HashMap<>();
try
{
session.parseBody(files);
final File src = new File(files.get("filename"));
// final File dst = new File(rootDir, parms.get("filename"));
//final File mydst = new File(parms.get("filename"));
String myString=parms.get("filename");
String fileName = myString.substring(myString.lastIndexOf("\\")+1);
String s = "/storage/sdcard0/www/"+fileName;
final File dst = new File(s);
//Files.copy(src.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
try {
copy(src, dst);
}catch (Exception e){
Log.e("CW","Error");
e.printStackTrace();
}
System.out.println(src.getAbsolutePath() + ": uploaded to: " + dst.getAbsolutePath());
return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, "ok i am ");
} catch (IOException ex)
{
} catch (ResponseException ex)
{
}
return getNotFoundResponse();
}
public 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();
}
private Response downloadFile(File file)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
} catch (FileNotFoundException ex)
{
// Logger.getLogger(MyWebServer.class.getName()).log(Level.SEVERE, null, ex);
}
return newFixedLengthResponse(Response.Status.OK, "application/octet-stream", fis, file.getTotalSpace());
}
private Response listDirectory(File file, Map<String, String> header, String uri)
{
String htmlCode = "<li><a href=\"http://%s\">%s</a></li>";
StringBuilder message = new StringBuilder("<ul>");
for (File f : file.listFiles())
message.append(String.format(htmlCode, header.get("host") + uri + f.getName(), f.getName()));
message.append("</ul>");
message.append("<form method=\"post\" enctype=\"multipart/form-data\">\n"
+ " <input type=\"file\" name=\"filename\" />\n"
+ " <input type=\"submit\" value=\"Send\" />\n"
+ "</form>");
return mynewFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, message.toString());
}
//@Override
private Response mynewFixedLengthResponse(Response.IStatus status, String mimeType, String message)
{
Response response = super.newFixedLengthResponse(status, mimeType, message);
response.addHeader("Accept-Ranges", "bytes");
return response;
}
protected Response getNotFoundResponse()
{
return newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Error 404, file not found.");
}
}
Любые идеи враг меня? – HelloCW
Я немного смущен - вы думаете о том, что 'final File src = new File (files.get (" filename ")),' где 'src' - это каталог? ИЛИ вы ищете наличие «Map files = new HashMap <>();', содержащий несколько записей, определяющих имена файлов загружаемых файлов? –
ishmaelMakitla