How to Download Files from Amazon S3 Bucket in Spring Boot

공부는 혼자하는 거·2023년 6월 26일
0

Spring Tip

목록 보기
43/52

Download Single File as Inmemory


    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)

Download as zip that Multiple Files from Amazon S3 Bucket in Spring Boot


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

profile
시간대비효율

0개의 댓글