How to insert media files to MediaStore using the MediaStore API insert with the proper file name instead of arbitrary name?

462 Views Asked by At

I'm trying to support scoped storage and trying to unify the implementation for dealing with the media files: inserting media files to mediaStore done successfully but with arbitrary name for ex: if the file name was geeks.jpg it actually creates it as ex 599345665432.jpg

fun writeImage(inputStream: InputStream, fileName: String): Uri? {
    val collectionUri = if (atLeastQ()) {
        MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
    } else {
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    }

    val imageDetails = ContentValues().apply {
        put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
        put(MediaStore.Images.Media.TITLE, fileName)
        if (atLeastQ()) put(MediaStore.Images.Media.IS_PENDING, 1)
    }

    val imageContentUri = contentResolver.insert(imageCollection, imageDetails)
    imageContentUri?.let {
        contentResolver.openOutputStream(it)?.use { outputImageFile ->
            inputStream.writeFully(outputImageFile)
        }

    if(atLeastQ()) {
         imageDetails.clear()
         imageDetails.put(MediaStore.Images.Media.IS_PENDING, 0)
         contentResolver.update(imageContentUri, imageDetails, null, null)
      }
    }
    return imageContentUri
}

private fun atLeastQ() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
2

There are 2 best solutions below

0
Louis Chabert On

This code works fine for me, but it works only for pictures:

public void saveFileToPhone(InputStream inputStream, String filename) {
    OutputStream outputStream;
    Context myContext = requireContext();
    try {
        if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.Q){
            ContentResolver contentResolver = requireContext().getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Downloads.DISPLAY_NAME,filename);
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
            Uri collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
            Uri fileUri = contentResolver.insert(collection, contentValues);
            outputStream = contentResolver.openOutputStream(Objects.requireNonNull(fileUri));
            Objects.requireNonNull(outputStream);

        }
    }catch (FileNotFoundException e) {

        e.printStackTrace();
    }
}
0
Anggrayudi H On

I would suggest using SimpleStorage because it will be simpler:

val desc = FileDescription("geeks", "", "image/jpeg")
val media = MediaStoreCompat.createImage(this, desc, ImageMediaDirectory.PICTURES)
media?.openOutputStream()?.use { outputStream ->
    inputStream.writeFully(outputStream)
}