媒体不允许主目录下载 [英] Primary directory Download not allowed for media
问题描述
尝试将 PDF 文件保存在下载目录中,但在 Android Q 之后 getExternalStoragePublicDirectory
完全弃用后,除了 DCIM 或图片文件夹之外,无法将文件保存在任何其他位置,因为以下例外试图在那里保存文件时被抛出.
Trying to save a PDF file in downloads directory, but after getExternalStoragePublicDirectory
got completely deprecated after Android Q, there is no way to save files in any other location than DCIM or Pictures folder as the following exception got thrown when trying to save file there.
IllegalArgumentException:主目录下载不允许content://media/external/images/media;允许的目录是 [DCIM,图片]
IllegalArgumentException: Primary directory Download not allowed for content://media/external/images/media; allowed directories are [DCIM, Pictures]
有以下代码.
private fun saveFile(input: ByteArray) {
val fileName = "myFile.pdf"
val outputStream = if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
val file = File(directory, fileName)
FileOutputStream(file)
} else {
val resolver = context.contentResolver
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "images/*")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
}
resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)?.let {
resolver.openOutputStream(it)
}
}
outputStream?.use { stream ->
stream.write(input)
}
}
显然,当将路径更改为 DIRECTORY_DCIM 时,一切都按预期工作,但由于要求,文件应像以前一样保存到下载中.将不胜感激任何帮助.
Obviously when changing the path to DIRECTORY_DCIM, everything works as expected, but due to requirements the file should be saved to downloads as previously. Would appreciate any help.
推荐答案
没有为文件保存设置正确的 Uri,对于下载应该是
Wasn't setting the correct Uri for file saving, for downloads it should be
resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues)
blackapps感谢指点.
这篇关于媒体不允许主目录下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!