上传脚本不会更新进度条

时间:2018-02-11 15:45:20

标签: android kotlin httpurlconnection secure-random x509trustmanager

我使用ssl将文件上传到Simple Auth保护的网页。它有效,但进度条不起作用,即它没有显示任何进展,突然之间就完成了。

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";
    }
 ?>    

我想,问题发生在pbF(fileSize.toDouble(), sentBytes.toDouble())区域。我将fileSize.toDouble()替换为bytesAvailable,但即使这样也没有改变行为。我把文件分块了,但是很长一段时间没有发生任何事情,然后进度条填满了,随后突然发生了什么事情&#34; Finished&#34;显示在日志中。

0 个答案:

没有答案