-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
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()
}