Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.t2r2.volleyexample
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Response
import com.android.volley.toolbox.Volley
import java.io.IOException
class MainActivity : AppCompatActivity() {
private lateinit var imageView: ImageView
private lateinit var imageButton: Button
private lateinit var sendButton: Button
private var imageData: ByteArray? = null
private val postURL: String = "https://ptsv2.com/t/54odo-1576291398/post" // remember to use your own api
companion object {
private const val IMAGE_PICK_CODE = 999
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageView = findViewById(R.id.imageView)
imageButton = findViewById(R.id.imageButton)
imageButton.setOnClickListener {
launchGallery()
}
sendButton = findViewById(R.id.sendButton)
sendButton.setOnClickListener {
uploadImage()
}
}
private fun launchGallery() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
private fun uploadImage() {
imageData?: return
val request = object : VolleyFileUploadRequest(
Method.POST,
postURL,
Response.Listener {
println("response is: $it")
},
Response.ErrorListener {
println("error is: $it")
}
) {
override fun getByteData(): MutableMap<String, FileDataPart> {
var params = HashMap<String, FileDataPart>()
params["imageFile"] = FileDataPart("image", imageData!!, "jpeg")
return params
}
}
Volley.newRequestQueue(this).add(request)
}
@Throws(IOException::class)
private fun createImageData(uri: Uri) {
val inputStream = contentResolver.openInputStream(uri)
inputStream?.buffered()?.use {
imageData = it.readBytes()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE) {
val uri = data?.data
if (uri != null) {
imageView.setImageURI(uri)
createImageData(uri)
}
}
super.onActivityResult(requestCode, resultCode, data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment