Send a file via HTTP POST with okhttp (Kotlin)

46 Views Asked by At

I'm trying to send a file from an Android device to a remote server by HTTP POST using okhttp library. This is the Kotlin code in the app:

class MyUploader {
    suspend fun makeRequest(fileUrl : String, str : String): String {
        val okHttpClient = OkHttpClient()
        return withContext(Dispatchers.IO) {
            parseResponse(okHttpClient.newCall(createRequest(fileUrl,str)).execute())
        }
    }

    private fun createRequest(fileUrl: String,str: String): Request {
        val requestBody = str.toRequestBody()
        val formBody: RequestBody = MultipartBody.Builder()
            .addFormDataPart("file", "log.csv")
            .addFormDataPart("app", "Roaming QOS APP")
            .addPart(requestBody)
            .build()

        return Request.Builder()
            .post(formBody)
            .url(fileUrl)
            .build()
    }

    private fun parseResponse(response: Response): String {
        val body = response.body?.string() ?: ""
        return body
    }

}

The makeRequest function is called with the following parameter:

fileUrl = "http://www.xxxxx.it/log.php"
str = the content of the file to be sent

And this is the PHP code on the server (the name of the script is log.php):

<?php

$file_path = "./";

$file_path = $file_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path) ){
    echo "success";
} else{
    echo "fail";
}
?>

The code is correctly called from the device but I get the following error on the server:

[Wed Mar 06 17:37:33.536882 2024] [:error] [pid 453] [client 151.25.30.103:35244] PHP Notice: Undefined index: file in /home/web/qosapp/log.php on line 6

Where is the error?

0

There are 0 best solutions below