Home > Software design >  How to upload image with Socket Ktor?
How to upload image with Socket Ktor?

Time:12-04

I want to send image in Socket. How can I do that with Ktor?

CodePudding user response:

The easiest way to upload an image with Socket Ktor is by using MultipartFormData, which is a Ktor feature that allows you to easily upload files. You can use the following code snippet to upload an image:

val multipart = MultipartFormDataContent()
val filePart = FileDataPart("filename", "image.jpg")
multipart.addPart(filePart)
val request = HttpRequestBuilder().apply {
    url("http://your-server-url")
    method = HttpMethod.Post
    body = multipart
}.build()
val response = client.submitFormWithBinaryData(request, multipart)

CodePudding user response:

AFAIK , you cannot do like http multi part upload in websockets directly.

Several things you can try.

  1. Try convert the image into Base64/Byte Array in client and send it to websocket server. Several things you may need to handle is, if you use byte array you might need to handle file headers in the byte array.

If you read file from image you can get like this and pass it to the websocket.

var arr = File(path).inputStream().use { it.readBytes() }

Downside of doing this is , if image size is higher it may not work as expected. And if you websocket sends it to multiple listening clients, it will be quite overload and leads to some delay while sending additional data with file byte array.

  1. Another best approach is to upload image to you sever using http multipart upload(Without socket) and send the image url to server. So url can be sent to clients listening to the particular socket. So the image data can be loaded in client only when required.

If you send byte array in webssocket for big image, the particular websocket response size will be higher than sending the image with image url.

Recommended approach will be method 2 mostly , except some specific use cases.

  • Related