Laurence
08/11/2020, 8:23 PMcall.receiveMultipart()
and then use the input stream, but when I test using postman it just hangs and doesn't fail with an error.
In Gradle I have:
// AWS S3
implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.7')
implementation 'com.amazonaws:aws-java-sdk-s3'
For the S3 client and upload function I am using:
private val s3Client = AmazonS3Client(
BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY)
).apply {
withRegion<AmazonWebServiceClient>(Regions.US_EAST_1)
setS3ClientOptions(
S3ClientOptions.builder()
.setPathStyleAccess(true).build()
)
}
fun uploadFileToS3(key: String, inputStream: InputStream, metadata: ObjectMetadata): PutObjectResult =
s3Client.putObject(BUCKET_NAME, key, inputStream, metadata)
Then the route is calling:
val multiPartData = call.receiveMultipart()
multiPartData.forEachPart { part ->
when (part) {
is PartData.FileItem -> {
val key = "profile-image/${part.originalFileName ?: "unknown-file"}"
part.streamProvider()
.use { inputStream ->
val bytes: ByteArray = IOUtils.toByteArray(inputStream)
val metadata = ObjectMetadata()
metadata.contentLength = bytes.size.toLong()
val byteArrayInputStream = ByteArrayInputStream(bytes)
AwsS3.uploadFileToS3(
key,
byteArrayInputStream,
metadata
)
}
}
else -> call.respond(HttpStatusCode.InternalServerError, JSONObject(mapOf("err" to "Error uploading file")))
}
}
call.respond(
HttpStatusCode.OK,
JSONObject(mapOf("msg" to "Image uploaded successfully"))
)
Hoping someone can spot where I'm going wrong 🙂 Thanks!Eric Grimsborn
08/11/2020, 9:43 PMLaurence
08/12/2020, 6:25 AMEric Grimsborn
08/12/2020, 9:22 AMawait put("/uploadurl", file);
to
const uploadUrl = await get("/get-upload-url");
await put(uploadUrl, file);
without having to handle all the multipart stuff which means much less code to write and maintain overall