【问题标题】:Retrofit image download works but the file is always corrupted改造图像下载有效,但文件总是损坏
【发布时间】: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


【解决方案1】:

原来我是个白痴。我使用的是Retrofit 实例,而该实例使用的是MoshiConverter,这导致内容长度发生更改,因此文件已损坏。通过使用不带MoshiConverterRetrofit 实例解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 2019-05-28
    • 1970-01-01
    相关资源
    最近更新 更多