milosev.com
  • Home
    • List all categories
    • Sitemap
  • Downloads
    • WebSphere
    • Hitachi902
    • Hospital
    • Kryptonite
    • OCR
    • APK
  • About me
    • Gallery
      • Italy2022
      • Côte d'Azur 2024
    • Curriculum vitae
      • Resume
      • Lebenslauf
    • Social networks
      • Facebook
      • Twitter
      • LinkedIn
      • Xing
      • GitHub
      • Google Maps
      • Sports tracker
    • Adventures planning
  1. You are here:  
  2. Home

Upload images from Android Kotlin to Web Api .NET Core - first Example

Details
Written by: Stanko Milosev
Category: Android
Published: 20 February 2024
Last Updated: 24 February 2024
Hits: 773

First problem, if you want to upload hardcoded path to the image like /sdcard/Download/IMG_20240120_133805.jpg, you will need external storage permission

Upload image to virtual device like I already wrote here

Here is ASP.NET Web Api Core example

In order to work in all versions in AndroidManifest.xml I have added:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
Please notice if you use MANAGE_EXTERNAL_STORAGE most probably you app will be rejected on play store

To check storage permission for all versions of Android I have used following code:

@RequiresApi(Build.VERSION_CODES.R)
fun checkLocalStoragePermission() {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
		if (!Environment.isExternalStorageManager()) {
			val uri = Uri.parse("package:${BuildConfig.APPLICATION_ID}")
			startActivity(
				Intent(
					Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
					uri
				)
			)
		}
	}
}
In app\build.gradle.kts I have added buildConfig = true,
buildFeatures {
	buildConfig = true
}
so that piece of code
val uri = Uri.parse("package:${BuildConfig.APPLICATION_ID}")
works


Also, for retrofit I will need permission:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

In app\build.gradle.kts I have added retrofit:

implementation( "com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("com.squareup.retrofit2:converter-scalars:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")

Then I have added WebApiService interface:

import okhttp3.MultipartBody
import retrofit2.Call
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part

interface WebApiService {
    @Multipart
    @POST("api/UploadPictures/UploadImage")
    fun uploadImage(
        @Part image: MultipartBody.Part?
    ): Call<UploadResponse>
}

data class UploadResponse(
    @SerializedName("message")
    val message: String
)
Retrofit is almost the same as I already explained here, except the post method:
val imageFile = File(imagePath)
val requestBody = imageFile.asRequestBody("image/*".toMediaTypeOrNull())
val imagePart = MultipartBody.Part.createFormData("image", imageFile.name, requestBody)

val apiService = retrofit.create(WebApiService::class.java)
val webApiRequest = apiService.uploadImage(imagePart)
Here how the whole file looks like:
import android.app.AlertDialog
import android.util.Log
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.RequestBody.Companion.asRequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

class UploadImageRetrofit {
    fun uploadImage(imagePath: String, alertDialogBuilder: AlertDialog.Builder): String? {

        val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
            override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                Log.i(MainActivity::class.simpleName, "checkClientTrusted")
            }

            override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                Log.i(MainActivity::class.simpleName, "checkServerTrusted")
            }

            override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
        })
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, trustAllCerts, java.security.SecureRandom())

// Create an ssl socket factory with our all-trusting manager
        val sslSocketFactory = sslContext.socketFactory

// connect to server
        val client = OkHttpClient.Builder()
            .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
            .hostnameVerifier { _, _ -> true }.build()


        val retrofit = Retrofit.Builder()
            .baseUrl("https://10.0.2.2:7181/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val imageFile = File(imagePath)
        val requestBody = imageFile.asRequestBody("image/*".toMediaTypeOrNull())
        val imagePart = MultipartBody.Part.createFormData("image", imageFile.name, requestBody)

        val apiService = retrofit.create(WebApiService::class.java)
        val webApiRequest = apiService.uploadImage(imagePart)

        webApiRequest.enqueue(object : Callback<UploadResponse> {
            override fun onResponse(call: Call<UploadResponse>, response: Response<UploadResponse>) {

                if (!response.isSuccessful) {
                    alertDialogBuilder.setMessage(response.errorBody()!!.charStream().readText())
                        .setCancelable(false)
                        .setNeutralButton("OK") { dialog, _ ->
                            dialog.dismiss()
                        }

                    val alert = alertDialogBuilder.create()
                    alert.setTitle("Error")
                    alert.show()
                } else {
                    alertDialogBuilder.setMessage("Response: ${response.body()?.message.toString()}")
                        .setCancelable(false)
                        .setNeutralButton("OK") { dialog, _ ->
                            dialog.dismiss()
                        }

                    val alert = alertDialogBuilder.create()
                    alert.setTitle("Success")
                    alert.show()
                }
            }

            override fun onFailure(call: Call<UploadResponse>, t: Throwable) {
                alertDialogBuilder.setMessage(t.message)
                    .setCancelable(false)
                    .setNeutralButton("OK") { dialog, _ ->
                        dialog.dismiss()
                    }

                val alert = alertDialogBuilder.create()
                alert.setTitle("Error")
                alert.show()
            }

        })

        return null
    }
}

MainActivity.kt:

import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.View
import androidx.annotation.RequiresApi

class MainActivity : AppCompatActivity() {
    @RequiresApi(Build.VERSION_CODES.R)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        checkLocalStoragePermission()
    }

    fun onUploadImageButtonClick(view: View) {
        val uploadImageRetrofit = UploadImageRetrofit()
        val alertDialogBuilder = AlertDialog.Builder(this@MainActivity)
        uploadImageRetrofit.uploadImage("/sdcard/Download/IMG_20240120_133805.jpg", alertDialogBuilder)
    }

    @RequiresApi(Build.VERSION_CODES.R)
    fun checkLocalStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                val uri = Uri.parse("package:${BuildConfig.APPLICATION_ID}")
                startActivity(
                    Intent(
                        Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
                        uri
                    )
                )
            }
        }
    }
}
Download from here

---

Web API .Net Core controller:
using Microsoft.AspNetCore.Mvc;

namespace UploadPictures.Controllers;

[ApiController]
[Route("api/[controller]")]
public class UploadPicturesController : Controller
{

    private readonly string _uploadPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UploadPictures", "uploads");

    [HttpPost]
    [Route("UploadImage")]
    public async Task<IActionResult> UploadImage()
    {
        try
        {
            if (!Request.HasFormContentType)
            {
                return BadRequest("Invalid content type. Must be multipart/form-data.");
            }

            var form = await Request.ReadFormAsync();
            var file = form.Files.FirstOrDefault();

            if (file == null)
            {
                return BadRequest("No image file found in the request.");
            }

            // Generate a unique filename
            var filename = Path.GetRandomFileName() + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(_uploadPath, filename);

            // Create the upload directory if it doesn't exist
            Directory.CreateDirectory(_uploadPath);

            // Save the uploaded file
            await using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            return Ok(new { message = "Image uploaded successfully." });
        }
        catch (Exception ex)
        {
            // Log the error for debugging
            Console.WriteLine(ex.ToString());
            return StatusCode(500, "Internal server error.");
        }
    }
}
Download Visual Studio .NET Core example from here

Upload images to virtual device

Details
Written by: Stanko Milosev
Category: Android
Published: 20 February 2024
Last Updated: 20 February 2024
Hits: 673
Open device in Device explorer:

And click on button upload

Select images from local storage

Details
Written by: Stanko Milosev
Category: Android
Published: 17 February 2024
Last Updated: 17 February 2024
Hits: 666
My example how to select images from local storage:
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    private val galleryLauncher =
        this.registerForActivityResult(ActivityResultContracts.GetMultipleContents()) { images ->
            for (image in images) {
                println(image.path)
            }
        }

    private fun openGallery() {
        galleryLauncher.launch("image/*")
    }

    fun onButtonClick(view: View) {
        openGallery();
    }
}

Binding

Details
Written by: Stanko Milosev
Category: Android
Published: 10 August 2023
Last Updated: 10 August 2023
Hits: 854
  • kotlin
There are two types of binding in Android: View binding and Data Binding.

View binding example:

binding.name.text = viewModel.name
binding.button.setOnClickListener { viewModel.userClicked() }
Data Binding example
<Button
android:id="@+id/btnMyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Settings"
android:onClick="@{() -> viewModel.onButtonClick()}" />
According to Android for Developers both can be used:
Comparison with data binding
View binding and data binding both generate binding classes that you can use to reference views directly. However, view binding is intended to handle simpler use cases and provides the following benefits over data binding:

Faster compilation: view binding requires no annotation processing, so compile times are faster.
Ease of use: view binding doesn't require specially tagged XML layout files, so it's faster to adopt in your apps. Once you enable view binding in a module, it applies to all of that module's layouts automatically.
On the other hand, view binding has the following limitations compared to data binding:

View binding doesn't support layout variables or layout expressions, so it can't be used to declare dynamic UI content straight from XML layout files.
View binding doesn't support two-way data binding.
Because of these considerations, in some cases it's best to use both view binding and data binding in a project. You can use data binding in layouts that require advanced features and use view binding in layouts that don't.
  1. Get data from Activity
  2. Simple MVVM example in Kotlin
  3. Mock context
  4. MockWebServer example

Subcategories

C#

Azure

ASP.NET

JavaScript

Software Development Philosophy

MS SQL

IBM WebSphere MQ

MySQL

Joomla

Delphi

PHP

Windows

Life

Lazarus

Downloads

Android

CSS

Chrome

HTML

Linux

Eclipse

Page 141 of 165

  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145