NanoHttpd / nanohttpd

Tiny, easily embeddable HTTP server in Java.
http://nanohttpd.org
BSD 3-Clause "New" or "Revised" License
6.96k stars 1.7k forks source link

how to run server and display index.html and push image to index.html #648

Open kun510 opened 2 months ago

kun510 commented 2 months ago

I have created a server and I have displayed the index.html file on the server, but now I want to transmit that image to the server and display it in index.html, what should I do?

my code :

class SimpleHTTPServer(port: Int,private val context: Context) : NanoHTTPD(port) {

override fun serve(session: IHTTPSession): Response {
    return when {
        session.uri.endsWith("/") -> serveFile("index.html")
        else -> serveFile(session.uri.substring(1))
    }
}

private fun serveFile(fileName: String): Response {
    return try {
        val assetManager = context.assets
        val inputStream = assetManager.open(fileName)

        val mimeType = when {
            fileName.endsWith(".html") -> "text/html"
            fileName.endsWith(".jpg") -> "image/jpeg"
            fileName.endsWith(".png") -> "image/png"
            fileName.endsWith(".js") -> "application/javascript"
            else -> "application/octet-stream"
        }

        newFixedLengthResponse(Response.Status.OK, mimeType, inputStream, inputStream.available().toLong())

    } catch (e: IOException) {
        Log.e("ImageStreamer", "File not found: $fileName", e)
        newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "File not found")
    }
}

}

index.html :

< b o d y > < i m g class="center" id="Image" src="logo.jpg"/> </b o d y>

start server: private fun startServer() { server= SimpleHTTPServer(8080,context) server?.start() Log.d(tag, "Server started")
}

send image on server: private fun sendImageToServer(base64Image: String) { val url = URL(SERVER_CONNECT) Thread { val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "POST" connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") connection.doOutput = true

        val postData = "file=$base64Image"

        OutputStreamWriter(connection.outputStream).use {
            it.write(postData)
            it.flush()
        }

        val responseCode = connection.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) {
            Log.d("ImageStreamer", "Image uploaded successfully.")
        } else {
            Log.d("ImageStreamer", "Error uploading image: $responseCode")
        }
    }.start()
}