How to upload files to NanoHTTPD Server in Android from a Java client running on Desktop connected over WiFi

41 views Asked by At

I have the following implementation in a Java client application that I'm trying to upload files to a NanoHTTPD server :

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class RevFileUploadTask {
    private static final String REV_SERVER_URL = "http://192.168.16.57:8090/upload";
    private static final String BOUNDARY = "--------------------------1234567890abcdef";

    public void revUploadFiles(List<File> selectedFiles) {
        if (selectedFiles == null || selectedFiles.isEmpty()) {
            System.err.println("No files selected for upload.");
            return;
        }

        try {
            URL url = new URL(REV_SERVER_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            try (OutputStream outputStream = connection.getOutputStream();
                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true)) {

                for (File file : selectedFiles) {
                    writer.append("--" + BOUNDARY).append("\r\n");
                    writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"")
                            .append("\r\n");
                    writer.append("Content-Type: " + "application/octet-stream").append("\r\n");
                    writer.append("\r\n");

                    try (FileInputStream fileInputStream = new FileInputStream(file)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }

                    writer.append("\r\n");
                }

                writer.append("--" + BOUNDARY + "--").append("\r\n");
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // Handle a successful response from the server
                // You can read the server response here if needed
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    System.out.println("Server response: " + response.toString());
                }
            } else {
                // Handle an error response from the server
                System.err.println("Error: " + responseCode);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
            System.err.println("Error: " + ex.getMessage());
        }
    }
}

The Server :

package com.iksync.rev_http_web_server;

import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Response.Status;
import okio.BufferedSink;
import okio.Okio;

public class RevAndroidHttpServer extends NanoHTTPD {

    public RevAndroidHttpServer(int port) {
        super(port);
    }

    public static void revInit(int port) {
        RevAndroidHttpServer server = new RevAndroidHttpServer(port);

        try {
            server.start();
            System.out.println("Server started on port " + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Response serve(IHTTPSession revSession) {
        Method method = revSession.getMethod();

        try {
            // Retrieve the query parameters map
            Map<String, List<String>> queryParams = revSession.getParameters();

            // Check if the "revFilePath" parameter exists
            if (Method.POST.equals(method)) {
                try {
                    // Parse the request to get uploaded files
                    Map<String, String> files = new HashMap<>();
                    revSession.parseBody(files);

                    for (Map.Entry<String, String> entry : files.entrySet()) {
                        String fieldName = entry.getKey();
                        String tempFilePath = entry.getValue();

                        Log.d("MyApp", ">>> fieldName " + fieldName);
                        Log.d("MyApp", ">>> tempFilePath " + tempFilePath);
                    }

                    return newFixedLengthResponse("Files uploaded successfully.");
                } catch (IOException e) {
                    e.printStackTrace();
                    return newFixedLengthResponse("Error uploading files: " + e.getMessage());
                } catch (ResponseException e) {
                    e.printStackTrace();
                    return newFixedLengthResponse("Error: " + e.getMessage());
                }
            } else {
                // Handle the case where "revFilePath" parameter is missing
                return newFixedLengthResponse(Status.BAD_REQUEST, NanoHTTPD.MIME_PLAINTEXT,
                        "Missing 'revFilePath' parameter");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "Internal server error");
        }
    }
}

However :

String fieldName = entry.getKey();  
String tempFilePath = entry.getValue();  

are empty.

How can I fix this? Where am I going wrong?

Thank you all in advance.

0

There are 0 answers