How to upload an image to a server using http request in kotlin?

I have written code to upload images to the server using kotlin, that is, the user takes a picture through the camera then displays the image in the imageView when the user clicks the send button, I want the image from ImageView to be sent to the server, but I don't know how to change the image from ImageView be a file that can be sent to the server.

I have designed code to capture image and set the image in image view to preview it but not getting idea to upload it to the server using http request.

for opening camera and setting image into imageview:

private fun openCamera(){

    val values = ContentValues()

    values.put(MediaStore.Images.Media.TITLE, "New Picture")

    values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera")

    private fun openCamera() {
    val values = ContentValues()
    values.put(MediaStore.Images.Media.TITLE, "New Picture")
    values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera")
    image_uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
    startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {

    when (requestCode) {
        PERMISSION_CODE_CAM -> {
            if (grantResults.size!! > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera()
            } else {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (resultCode == Activity.RESULT_OK && resultCode == IMAGE_CAPTURE_CODE) {
        imageView.setImageURI(image_uri)
    }

}

I want to upload image to server using http request, I am getting many codes in java but not in kotlin. I am not getting any idea to upload in kotlin.

Upvotes: 3

Views: 19324

Answers (4)

sarjeet singh
sarjeet singh

Reputation: 551

this is image upload using kotlin Retrofit code 100% working

 private fun UploedImage(User_id:String , newfile: File) {
        Commons.showProgressDialog(this@StoreDetailActivity)

       
        //creating a file
        var requestFile: RequestBody? = null
        var document: MultipartBody.Part
        var ImageUloloadgetCall: Call<ImageUloloadgetUrlModel?>? = null
        if (newfile != null) {
            val MEDIA_TYPE_IMAGE = "image/*".toMediaTypeOrNull()

            requestFile = create(MEDIA_TYPE_IMAGE, newfile)


            document = createFormData(
                "image",
                newfile.getName(),
                requestFile
            )

            val userId= create("text/plain".toMediaTypeOrNull(), User_id)

            ImageUloloadgetCall = getApiInstance().ImageUpload(
                alldata,
                document
            )
        }
        ImageUloloadgetCall!!.enqueue(object : Callback<ImageUloloadgetUrlModel?> {
            override fun onResponse(
                call: Call<ImageUloloadgetUrlModel?>,
                response: Response<ImageUloloadgetUrlModel?>
            ) {
                dismissProgressDialog()
                if (!response.isSuccessful()) {
                    Log.d(
                        TAG,
                        "onResponse: fail " + response.code()
                    )
                    Toast.makeText(
                        this@StoreDetailActivity,
                        "" + response.message(),
                        Toast.LENGTH_SHORT
                    ).show()
                    return
                }
                Log.d(
                    TAG,
                    "onResponse: success" + response.code() + response.body()
                )
                if (response.body() != null) {
                    var imageUloloadgetUrlModel: ImageUloloadgetUrlModel? = null
                    try {
                        imageUloloadgetUrlModel = response.body()



                         
                    } catch (e: Exception) {
                        Toast.makeText(
                            this@StoreDetailActivity,
                            "Error in response",
                            Toast.LENGTH_SHORT
                        ).show()
                        return
                    }
                } else {
                    Toast.makeText(
                        this@StoreDetailActivity,
                        "Invalid response from server",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            override fun onFailure(call: Call<ImageUloloadgetUrlModel?>, t: Throwable) {
                dismissProgressDialog()
            }
        })
    }

Upvotes: 0

Shamsuddin Lelin
Shamsuddin Lelin

Reputation: 9

Api Interface

@Multipart
@POST("your_url")
suspend fun uploadImage(
    @Part file:MultipartBody.Part
): Response<String>

Kotlin code

        val file: File = ImagePicker.getFile(data)!!


        val requestFile =RequestBody.create("multipart/form-data".toMediaTypeOrNull(),file)
        val requestFile=RequestBody.create(MediaType.parse("image/*"),file)
        val body = MultipartBody.Part.createFormData("profile_picture", file.name, requestFile)
        uploadImage(body)

Upvotes: 0

Asad Ali Choudhry
Asad Ali Choudhry

Reputation: 5271

As this is question is still open. We can use OKHTTP library which is very easy to use and we have to write very less code. Here I have written a detailed article on the topic

Upload Image or File to Server in Android Kotlin

I am not going to copy the same code again, I have written a UploadUtility class. Just copy it in your project from the above link and it will do the rest.

Upvotes: -1

No Body
No Body

Reputation: 681

You can use these functions to capture an image by the camera:

public static Uri getTakenPictureUri(Context mContext, Intent data) {
    Uri selectedImage = data.getData();
    String[] filePathColumn = {MediaStore.Images.Media.DATA};

    Cursor cursor = mContext.getContentResolver().query(selectedImage,
            filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String picturePath = cursor.getString(columnIndex);
    cursor.close();

    picturePath = "file://" + picturePath;
    LogHelper.trace("Selected file uri:" + picturePath);

    return Uri.parse(picturePath);
}

public static File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = MyPharmacy.getmInstance().getExternalCacheDir();
    LogHelper.trace("createImageFile:" + storageDir.getAbsolutePath());
    File image = File.createTempFile(
            imageFileName,
            ".jpg",
            storageDir
    );
    return image;
}

public static File openCamera(Activity mActivity, int requestCode) {
    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    try {
        File photoFile = createImageFile();
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(MyPharmacy.getmInstance(), BuildConfig.APPLICATION_ID + ".provider", photoFile);
            camera.putExtra(MediaStore.EXTRA_OUTPUT,
                    photoURI);
            if (camera.resolveActivity(mActivity.getPackageManager()) != null) {
                mActivity.startActivityForResult(camera, requestCode);
                return photoFile;
            }
        }
    } catch (IOException ex) {
    }
    return null;
}

public static File openCamera(Fragment fragment, int requestCode) {
    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    try {
        File photoFile = createImageFile();
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(MyPharmacy.getmInstance(), BuildConfig.APPLICATION_ID + ".provider", photoFile);
            camera.putExtra(MediaStore.EXTRA_OUTPUT,
                    photoURI);
            if (camera.resolveActivity(fragment.getActivity().getPackageManager()) != null) {
                fragment.startActivityForResult(camera, requestCode);
                return photoFile;
            }
        }
    } catch (IOException ex) {
    }
    return null;
}

Then use below codes to upload it by retrofit

public static void uploadImage(final String filePath,
                                           final String token,
                                           final APIResponseCallback<UploadResponse> cb) {
    if (filePath != null && !filePath.isEmpty()) {
        final File file = new File(filePath);
        if (file.exists()) {

            Glide.with(App.getmInstance().getContext()).load(file).asBitmap().override(700, 700).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                    OutputStream os = null;
                    try {
                        String realPath = StorageHelper.getRealPathFromUri(App.getmInstance().getContext(), Uri.fromFile(file));
                        os = new BufferedOutputStream(new FileOutputStream(file));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, os);
                        os.flush();
                        os.close();
                    } catch (java.io.IOException e) {
                        e.printStackTrace();
                    }


                    if (file != null) {
                        // creates RequestBody instance from file
                        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
                        // MultipartBody.Part is used to send also the actual filename
                        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                        // adds another part within the multipart request
                        String descriptionString = "Image";
                        RequestBody description = RequestBody.create(okhttp3.MultipartBody.FORM, descriptionString);
                        // executes the request
                        ServiceGenerator.getAPIServices().uploadImage(body, description, token).enqueue(new Callback<UploadResponse>() {
                            @Override
                            public void onResponse(Call<UploadResponse> call, Response<UploadResponse> response) {
                                if (response.isSuccessful()) {
                                    cb.onSuccess(response.body());
                                } else {
                                    checkError(response, token);
                                }
                            }

                            @Override
                            public void onFailure(Call<UploadResponse> call, Throwable t) {
                                cb.onError(t);
                            }
                        });
                    }
                }
            });
        }
    }
}

And API interface is:

@Multipart
@POST("Uploads/image/upload")
Call<UploadResponse> uploadImage(@Part MultipartBody.Part file,
                                             @Part("description") RequestBody description,
                                             @Query("access_token") String token);

Also, you can convert these codes to the kotlin equivalent.

Upvotes: -2

Related Questions