Advertisement
adi282123

MainActivity Multipart

Jan 18th, 2019
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.82 KB | None | 0 0
  1. fun uploadImage(imagePath: String)
  2.     {
  3.         var textToPost = nameToPostET.text.toString()
  4.  
  5.         val URL = "http://192.168.100.10/"
  6.         val gsonBuilder = GsonBuilder().setLenient()
  7.         val gson = gsonBuilder.create()
  8.  
  9.         val retrofit = Retrofit.Builder()
  10.             .baseUrl(URL)
  11.             .addConverterFactory(GsonConverterFactory.create(gson))
  12.             .build()
  13.  
  14.         val webApiInterface = retrofit.create(WEBApiInterface::class.java)
  15.  
  16.         val file = File(imagePath)
  17.  
  18.         val requestBody = RequestBody.create(MediaType.parse("*/*"), file)
  19.  
  20.         val fileToUpload = MultipartBody.Part.createFormData("upload_file", file.name, requestBody)
  21.  
  22.         val requestPOST = RequestBody.create(MediaType.parse("plain/text"), textToPost)
  23.  
  24.         var call = webApiInterface.uploadFile(fileToUpload, requestPOST)
  25.  
  26.         call.enqueue(object : Callback<FileResponse> {
  27.             override fun onFailure(call: Call<FileResponse>?, t: Throwable?) {
  28.                 Log.e("MainActivity", t.toString())
  29.             }
  30.  
  31.             override fun onResponse(call: Call<FileResponse>?, response: Response<FileResponse>?) {
  32.                 if(response!!.isSuccessful)
  33.                 {
  34.                     Log.v("MainActivity", "RESPONSE IS SUCCESSFUL")
  35.                     var message = response.body().message
  36.                     Toast.makeText(applicationContext, "MESSAGE --> "+message, Toast.LENGTH_LONG).show()
  37.  
  38.                     var postTestMessage = response.body().postTestMessage
  39.                     Toast.makeText(applicationContext, "POST TEST MESSAGE --> "+postTestMessage, Toast.LENGTH_LONG).show()
  40.                 }
  41.                 else
  42.                 {
  43.                     Log.e("MainActivity", "RESPONSE ISNT SUCCESSFUL")
  44.                 }
  45.             }
  46.  
  47.         })
  48.  
  49.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement