Last active
March 29, 2020 16:09
-
-
Save senthilsivanath/99408112456ea5352d24f49bc06c78d5 to your computer and use it in GitHub Desktop.
File upload in GCP and get expiry viewing link
This file contains 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
package com.company.service.controllers | |
import com.google.cloud.storage.BlobInfo | |
import com.google.cloud.storage.Storage | |
import com.google.cloud.storage.StorageOptions | |
import kotlinx.coroutines.reactive.awaitFirstOrNull | |
import org.springframework.http.MediaType | |
import org.springframework.http.codec.multipart.FilePart | |
import org.springframework.web.bind.annotation.PostMapping | |
import org.springframework.web.bind.annotation.RequestPart | |
import org.springframework.web.bind.annotation.RestController | |
import java.io.DataInputStream | |
import java.io.File | |
import java.io.FileInputStream | |
import java.util.* | |
import java.util.concurrent.TimeUnit | |
import kotlin.random.Random | |
@RestController | |
class LogoController{ | |
private fun checkFileExtension(fileName: String?): Boolean { | |
if (fileName != null && fileName.isNotEmpty() && fileName.contains(".")) { | |
val allowedExt = arrayOf(".png") | |
for (ext in allowedExt) { | |
if (fileName.endsWith(ext)) { | |
return true | |
} | |
} | |
throw Exception("file must be an image") | |
} | |
return false | |
} | |
@PostMapping("/imageUpload", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) | |
// Move the logic to service | |
suspend fun upload(@RequestPart("file") fileStream: FilePart): String { | |
val storage = StorageOptions.getDefaultInstance().service | |
checkFileExtension(fileStream.filename()) | |
val r = UUID.randomUUID().toString() | |
val uploadFileName = "student/$r.png" | |
val f = File("/tmp/$r.png") | |
fileStream.transferTo(f).awaitFirstOrNull() | |
val bytes = f.readBytes() | |
val bucketName = "profile-forgetcode" | |
val createdBlob = storage.create( | |
BlobInfo | |
.newBuilder(bucketName, uploadFileName) | |
.setContentType("image/png") | |
.build(), bytes | |
) | |
val url = storage.signUrl(createdBlob, 15, TimeUnit.MINUTES, Storage.SignUrlOption.withV4Signature()) | |
f.delete() | |
return url.toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment