Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// pick single image from gallery
private fun openGalleryImages() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(Intent.createChooser(intent, "Select Picture"), TYPE_IMAGE)
}
// get path
private fun getPath(uri: Uri): String {
val projection = arrayOf(MediaStore.Images.Media.DATA)
val cursor = managedQuery(uri, projection, null, null, null)
val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
return cursor.getString(column_index)
}
inner class UploadTask : AsyncTask<String, Int, Int>() {
override fun doInBackground(vararg p0: String?): Int? = uploadFileToServer()
private fun uploadFileToServer(): Int {
val conn: HttpURLConnection?
val dos: DataOutputStream?
val lineEnd = "\r\n"
val twoHyphens = "--"
val boundary = "*****"
var bytesRead: Int
var bytesAvailable: Int
var bufferSize: Int
val buffer: ByteArray
val maxBufferSize = 1 * 1024 * 1024
var serverResponseCode = 0
val sourceFile = File(getPath(mCurrentUri) )
val fileName = getTimeString()
if (!sourceFile.exists()) {
runOnUiThread { Toast.makeText(this@EditProfileActivity, "File don't exists", Toast.LENGTH_SHORT).show() }
} else {
try {
// open a URL connection to the Servlet
val fileInputStream = FileInputStream(sourceFile)
val url = URL(UrlConstants.FILE_UPLOAD)
// Open a HTTP connection to the URL
conn = url.openConnection() as HttpURLConnection?
conn?.doInput = true // Allow Inputs
conn?.doOutput = true // Allow Outputs
conn?.useCaches = false // Don't use a Cached Copy
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", fileName)
dos = DataOutputStream(conn?.outputStream)
dos.writeBytes(twoHyphens + boundary + lineEnd)
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd)
dos.writeBytes(lineEnd)
// create a buffer of maximum size
bytesAvailable = fileInputStream.available()
bufferSize = Math.min(bytesAvailable, maxBufferSize)
buffer = ByteArray(bufferSize)
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize)
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize)
bytesAvailable = fileInputStream.available()
bufferSize = Math.min(bytesAvailable, maxBufferSize)
bytesRead = fileInputStream.read(buffer, 0, bufferSize)
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd)
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd)
// Responses from the server (code and message)
serverResponseCode = conn!!.responseCode
val serverResponseMessage = conn.responseMessage
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode)
if (serverResponseCode == 200) {
runOnUiThread({
run { Toast.makeText(this@EditProfileActivity, "200 ", Toast.LENGTH_SHORT).show() }
})
}
//close the streams //
fileInputStream.close()
dos.flush()
dos.close()
} catch (ex: MalformedURLException) {
runOnUiThread({
run {
Toast.makeText(this@EditProfileActivity, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
})
Log.e("Upload file to server", "error: " + ex.message, ex)
} catch (e: Exception) {
e.printStackTrace()
runOnUiThread({
run {
Toast.makeText(this@EditProfileActivity, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
})
Log.e("TAG", "Exception : " + e.message, e)
}
}
return serverResponseCode
}
private fun getPath(uri: Uri): String {
val projection = arrayOf(MediaStore.Images.Media.DATA)
val cursor = managedQuery(uri, projection, null, null, null)
val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
return cursor.getString(column_index)
}
private fun getTimeString(): String {
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
return "JPEG_" + timeStamp + "_" + ".jpg"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.