Created
September 19, 2019 15:19
-
-
Save gpetuhov/741439e8617e25e52113f813b49767ba to your computer and use it in GitHub Desktop.
Retrofit download image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Retrofit upload selected image | |
// https://futurestud.io/tutorials/retrofit-2-how-to-download-files-from-server | |
// https://viblo.asia/p/android-kotlin-retrofit-2-download-file-63vKjapx52R | |
// === Retrofit service === | |
interface MediaService { | |
@Streaming | |
@GET | |
suspend fun downloadImage(@Url fileUrl: String): ResponseBody | |
} | |
// === Repository === | |
val response = mediaService.downloadImage(fileUrl) | |
writeResponseBodyToDisk(response) | |
private fun writeResponseBodyToDisk(body: ResponseBody): Boolean { | |
try { | |
val tempFile = createImageFile() | |
var inputStream: InputStream? = null | |
var outputStream: OutputStream? = null | |
try { | |
val fileReader = ByteArray(4096) | |
val fileSize = body.contentLength() | |
var fileSizeDownloaded: Long = 0 | |
inputStream = body.byteStream() | |
outputStream = FileOutputStream(tempFile) | |
while (true) { | |
val read = inputStream.read(fileReader) | |
if (read == -1) { | |
break | |
} | |
outputStream.write(fileReader, 0, read) | |
fileSizeDownloaded += read.toLong() | |
Timber.tag(TAG).d("file download: $fileSizeDownloaded of $fileSize") | |
} | |
outputStream.flush() | |
return true | |
} catch (e: IOException) { | |
return false | |
} finally { | |
inputStream?.close() | |
outputStream?.close() | |
} | |
} catch (e: IOException) { | |
return false | |
} | |
} | |
@Throws(IOException::class) | |
fun createImageFile(): File { | |
// Create an image file name | |
val timeStamp = getCurrentTimeString() | |
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) | |
return File.createTempFile( | |
timeStamp, /* prefix */ | |
".jpg", /* suffix */ | |
storageDir /* directory */ | |
) | |
} | |
private fun getCurrentTimeString() = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment