1

I am uploading a file to a Simple Auth protected web-page using ssl. It works, but the progress bar is not working, ie, it shows no progress and all of a sudden it's finished.

private fun hochladen(dn: String?): Int {
    var upLoadServerUri = "https://www.example.com/upload.php"
    var conn: HttpURLConnection?
    var dos: DataOutputStream?
    val lineEnd = "\r\n"
    val twoHyphens = "--"
    val boundary = "*****"
    var bytesRead: Int
    var bytesAvailable: Int
    var bufferSize: Int
    val buffer: ByteArray
    val sourceFile = File(dn)


    if (!sourceFile.isFile) {
        runOnUiThread { Log.e(TAG, "Not found") }
        return 0

    } else {
        try { 
            val fileSize = sourceFile.length()
            val fileInputStream = FileInputStream(sourceFile)
            val url = URL(upLoadServerUri)
            Authenticator.setDefault(object : Authenticator() {
                override fun getPasswordAuthentication(): PasswordAuthentication {
                    return PasswordAuthentication(getString(R.string.nutzername), getString(R.string.passwort).toCharArray())
                }
            })

            var sentBytes: Long = 0
            HttpsURLConnection.setDefaultHostnameVerifier(NullHostNameVerifier())
            val context = SSLContext.getInstance("TLS")
            context.init(null, arrayOf<X509TrustManager>(NullX509TrustManager()), SecureRandom())
            HttpsURLConnection.setDefaultSSLSocketFactory(context.socketFactory)

            conn = url.openConnection() as HttpURLConnection
            conn.doInput = true
            conn.doOutput = true

            conn.useCaches = false
            conn.requestMethod = "POST"
            conn.setRequestProperty("Connection", "Keep-Alive")
            conn.setRequestProperty("ENCTYPE", "multipart/form-data")
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary)
            conn.setRequestProperty("uploaded_file", dn)

            dos = DataOutputStream(conn.outputStream)

            dos.writeBytes(twoHyphens + boundary + lineEnd)
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"$dn\"$lineEnd")

            dos.writeBytes(lineEnd)

            bytesAvailable = fileInputStream.available()

            bufferSize = bytesAvailable
            buffer = ByteArray(bufferSize)
            d(TAG,bytesAvailable.toString()+", "+bufferSize)

            bytesRead = fileInputStream.read(buffer, 0, bufferSize)

            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize)
                bytesAvailable = fileInputStream.available()
                bufferSize = bytesAvailable
                bytesRead = fileInputStream.read(buffer, 0, bufferSize)
                sentBytes += bytesRead.toLong()
                pbF(fileSize.toDouble(), sentBytes.toDouble())
                d(TAG,fileSize.toString()+", "+sentBytes.toString())
            }

            dos.writeBytes(lineEnd)
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd)

            val serverResponseCode = conn.responseCode

            if (serverResponseCode == 200) {
                runOnUiThread {
                    Log.i(TAG, "Finished")
                    }
            }
            fileInputStream.close()
            dos.flush()
            dos.close()
        } catch (ex: MalformedURLException) {
            ex.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }
}

private fun pbF(end: Double, now: Double) {
    runOnUiThread {
        val progress = 100 / end * now
        if (progress <= 100)
            pbProgress.progress = progress.toInt()
    }
}    

https://www.example.com/upload.php:

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

I thought, the problem was in the pbF(fileSize.toDouble(), sentBytes.toDouble())area. I replaced fileSize.toDouble() with bytesAvailable, but even that did not change the behaviour. I chunked the file but then for quite some time nothing happened, then the progress bar filled, to be followed by nothing happening to all of a sudden "Finished" to show up in the log.

Vitalis Hommel
  • 990
  • 2
  • 8
  • 20
  • The code doesn't even compile... In the pbF method, end and start are undefined. And using findViewById every time the method is called is a waste of memory – Zoe Feb 11 '18 at 15:51
  • I said why it doesn't compile. End and start in the pbF method are not defined. You're most likely using the wrong var to calculate the percentage – Zoe Feb 11 '18 at 16:10
  • Fixed. Now what? – Vitalis Hommel Feb 11 '18 at 16:16
  • So it was just a copy-paste error? The incompatible vars there could have been the actual problem – Zoe Feb 11 '18 at 16:17
  • Zoe, I translated the code for non german speakers to understand and I missed translating the parameters passed to the function. The pbF works, but it gets the wrong data. So the issue is to be found in the code the pbF is called from. – Vitalis Hommel Feb 11 '18 at 16:19
  • Have you seen [this](https://stackoverflow.com/a/4352073/6296561)? – Zoe Feb 11 '18 at 16:58
  • Yes. It turns out, the bottleneck is `val serverResponseCode = conn.responseCode` – Vitalis Hommel Feb 11 '18 at 19:08

0 Answers0