-
Notifications
You must be signed in to change notification settings - Fork 5
/
UploadService.scala
54 lines (47 loc) · 1.47 KB
/
UploadService.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package services
import java.io.File
import play.api.Logger
import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData
import play.api.mvc.Request
import java.util.UUID
import play.api.Play
import play.api.Play.current
import utils.S3Utility
object UploadService extends UploadService {
val s3Utility: S3Utility = S3Utility
}
trait UploadService {
private val log: Logger = Logger(this.getClass)
val s3Utility: S3Utility
/**
* Get file from the request and move it in your location
*
* @param request
* @return
*/
def uploadFile(request: Request[MultipartFormData[TemporaryFile]]): String = {
log.error("Called uploadFile function" + request)
request.body.file("file").map { file =>
import java.io.File
val filename = file.filename
val contentType = file.contentType
log.error(s"File name : $filename, content type : $contentType")
val uniqueFile = new File(s"/tmp/${UUID.randomUUID}_$filename")
file.ref.moveTo(uniqueFile, true)
if (Play.isProd) {
try {
val bucket = s3Utility.getBucketByName("test").getOrElse(s3Utility.createBucket("test"))
val result = s3Utility.createObject(bucket, filename, uniqueFile)
s"File uploaded on S3 with Key : ${result.key}"
} catch {
case t: Throwable => log.error(t.getMessage, t); t.getMessage
}
} else {
s"File(${filename}) uploaded"
}
}.getOrElse {
"Missing file"
}
}
}