fun downloadByFileType(fileType: FileType, path:String): ByteArray {
val bucket =
awsProperty.s3.bucket
val s3object: S3Object = amazonS3.getObject(GetObjectRequest(bucket, path))
val inputStream: InputStream = s3object.objectContent
val outputStream =
ByteArrayOutputStream()
inputStream.use { inputStream ->
outputStream.use { output ->
var len: Int
val buffer = ByteArray(4096)
while (inputStream.read(buffer, 0, buffer.size).also { len = it } != -1) {
output.write(buffer, 0, len)
}
return output.toByteArray()
}
}
}
httpHeaders.contentType = contentType
httpHeaders.contentLength = bytes.size.toLong()
httpHeaders.setContentDispositionFormData("attachment", "${FilenameUtils.getBaseName(path)}.${fileType.name}")
return ResponseEntity(bytes, httpHeaders, HttpStatus.OK)
fun downloadZip(response: HttpServletResponse, filenames: List<String>): StreamingResponseBody {
val bucket =
awsProperty.s3.bucket
val BUFFER_SIZE = 1024
if (filenames.isEmpty()) throw RuntimeException("empty mastering file list")
val streamResponseBody = StreamingResponseBody { out ->
val zipOutputStream =
ZipOutputStream(response.outputStream)
lateinit var zipEntry: ZipEntry
lateinit var inputStream: InputStream
try {
for (filename in filenames) {
log.info { "filename" }
/* Retrieve file as object from S3 */
val s3Object =
amazonS3.getObject(GetObjectRequest(bucket, filename))
zipEntry = ZipEntry(filename)
inputStream = s3Object.objectContent
zipOutputStream.putNextEntry(zipEntry)
val bytes = ByteArray(BUFFER_SIZE)
var length: Int
inputStream.use { stream ->
while (stream.read(bytes).also { length = it } >= 0) {
zipOutputStream.write(bytes, 0, length)
}
}
}
// set zip size in response
response.setContentLength((zipEntry.size).toInt())
} catch (e: IOException) {
e.printStackTrace()
} finally {
if (zipOutputStream != null) {
zipOutputStream.close()
}
}
}
response.contentType = "application/zip"
response.addHeader("Pragma", "no-cache")
response.addHeader("Expires", "0")
return streamResponseBody
}
response.setHeader("Content-Disposition", "attachment; filename=$orderId-$category.zip")
return ResponseEntity.ok(masteringService.downloadZip(orderId, category, response))
https://www.tutorialsbuddy.com/download-multiple-files-from-amazon-s3-in-spring-boot