【发布时间】:2020-05-27 14:33:59
【问题描述】:
我正在使用第三方库打开图库和相机。我 已经完成了那部分。现在,当我选择多个图像或单个 图像,从第三方库中获取 URI 数组。现在,我创建了文件 在应用程序包文件夹中并能够创建它。但是当我检查下 app 文件夹,图片大小为 0 字节。我也在保存路径 在本地数据库上,稍后将使用多部分将其上传到服务器上。以下 是我的代码。
打开相册和相机
private fun openPicker() {
PhotoPickerFragment.newInstance(
multiple = true,
allowCamera = true,
maxSelection = 5,
theme = R.style.ChiliPhotoPicker_Light
).show(childFragmentManager, "picker")
}
获取选定的图像路径 URI 并使用 createFile 将路径保存到本地数据库
override fun onImagesPicked(photos: ArrayList<Uri>) {
Log.e("TAG", "pic" + photos.joinToString(separator = "\n") { it.toString() })
fileList = ArrayList<File>()
try {
photos.forEachIndexed { index, e ->
println("$e at ${photos[index].path}")
val destinationFile: File = createImageFile()
fileList.add(destinationFile)
fileList.also {
// Get the file-name from the image-path
val destinationFilePath = it[index].absolutePath
val fileName =
destinationFilePath.substring(destinationFilePath.lastIndexOf("/") + 1)
val attachment = AttachSiteImage()
attachment.apply {
callLoggingId = callLoggingIdForAttachment
attachmentFileName = fileName
attachmentPath = destinationFilePath
}
attachImageviewModel?.addAttachFromApi(attachment)
}
}
Log.e("TAG", "Path->" + fileList.size)
} catch (ex: FileAlreadyExistsException) {
// sourceFile.delete()
cl_attachments_main_container.showSnackBar(
if (!ex.localizedMessage.isNullOrEmpty())
ex.localizedMessage
else
ex.stackTrace.toString(),
Snackbar.LENGTH_SHORT
)
} catch (ex: IOException) {
// sourceFile.delete()
cl_attachments_main_container.showSnackBar(
if (!ex.localizedMessage.isNullOrEmpty())
ex.localizedMessage
else
ex.stackTrace.toString(),
Snackbar.LENGTH_SHORT
)
}
}
创建将存储照片的文件
@Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File? = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"${callLoggingIdForAttachment}_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
}
【问题讨论】:
-
好吧,您的代码使用
createTempFile创建了一个空文件,并且似乎没有向其中写入任何内容。如果addAttachFromApi应该这样做,请展示它! -
@AlexeyRomanov 是的。我可以在 package->files 下看到 0bytes 的文件。 attachImageviewModel?.addAttachFromApi(attachment) 这一行将图像从设备添加到本地数据库。我想我必须在选择图像捕获或图像时将文件复制到 package->files 文件夹