【发布时间】:2023-04-01 09:15:01
【问题描述】:
这是我的改造 API:
@GET
suspend fun downloadMedia(@Url url: String): Response<ResponseBody>
这是实际从 URL 下载图像并将其保存到设备存储的代码:
override fun downloadMedia(url: String): Flow<RedditResult<DownloadState>> = flow {
preferences.downloadDirFlow.collect {
if (it.isEmpty()) {
emit(RedditResult.Success(DownloadState.NoDefinedLocation))
} else {
// Actually download
val response = authRedditApi.downloadMedia(url)
if (response.isSuccessful) {
val treeUri = context.contentResolver.persistedUriPermissions.firstOrNull()?.uri
treeUri?.let { uri ->
val directory = DocumentFile.fromTreeUri(context, uri)
val file = directory?.createFile(
response.headers()["Content-Type"] ?: "image/jpeg",
UUID.randomUUID().toString().replace("-", ""))
file?.let {
context.contentResolver.openOutputStream(file.uri)?.use { output ->
response.body()?.byteStream()?.copyTo(output)
output.close()
emit(RedditResult.Success(DownloadState.Success))
}
} ?: run {
emit(RedditResult.Error(Exception("Unknown!")))
}
}
} else {
emit(RedditResult.Error(IOException(response.message())))
}
}
}
}
文件已下载并且大小正确(以 MB 为单位),但它以某种方式损坏,尺寸为 0x0 并且只是一个空白图像(在我的 PC 上它甚至无法打开)。
我真的不知道我做错了什么,因为文件正在被创建和写入正常(这对于 SAF 本身来说很困难)。
编辑:我也尝试过在 API 函数上使用和不使用 @Streaming,结果相同。
【问题讨论】:
-
correct size in MB,MB 是不够的。每个字节都很重要。请以字节为单位告知文件大小。两者兼而有之。
标签: android kotlin retrofit2 okhttp storage-access-framework