如何在Android中使用NanoHTTPD修改代码以上传多个文件?

时间:2016-05-04 09:18:55

标签: android nanohttpd

我是NanoHTTPD的初学者,我学习了文档NanoHttpd save uploaded fileshttps://github.com/romsahel/simplewebserver

以下代码可以通过WiFi将单个文件上传到Android手机。

现在我希望将多个文件上传到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.");
    }

}

1 个答案:

答案 0 :(得分:0)

我是这样做的:

public Response serve(IHTTPSession session) {
if (uri.toLowerCase().contains("add_file".toLowerCase())) {

        Method method = session.getMethod();
        if (Method.PUT.equals(method) || Method.POST.equals(method)) {
            try {
                Map<String, String> files = new HashMap<>();
                session.parseBody(files);
            } catch (IOException ioe) {
                return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
            } catch (ResponseException re) {
                return newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
            }
        }
       HelloServer.LOGCONSOLE.info(method + " '" + uri + "' ");
        String msg = upload(session);
 return newFixedLengthResponse(msg);
    } 
 public upload(IHTTPSession session){
 Map<String, String> parms = session.getParms();
 // recuperate file names
String file1 = parms.get("input_file");
 String file2 = parms.get("filename1");
 String file3 = parms.get("myFile2");

// you must put numbers if file number more than 1

// source file is located in the temporary directory
// you can modify your temp direcory by eiditing NanoHTTPD.saveTmpFile
...
return String ... ;