3

尝试从 Amazon S3 中提取图像(返回S3ObjectInputStream)并将其发送到mandrill 电子邮件 api(采用 base64 编码的字符串)。如何在 Scala 中做到这一点?

4

3 回答 3

13

我还设法仅使用 Apache commons 来做到这一点;不确定哪种方法更好,但我想我会把这个答案留作记录:

import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.IOUtils

val bytes = IOUtils.toByteArray(stream)
val bytes64 = Base64.encodeBase64(bytes)
val content = new String(bytes64)
于 2013-02-07T15:21:22.417 回答
6

这是一种解决方案,可能还有其他更有效的解决方案。

val is = new ByteArrayInputStream(Array[Byte](1, 2, 3)) // replace by your InputStream
val stream = Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte)
val bytes = stream.toArray
val b64 = new sun.misc.BASE64Encoder().encode(bytes)

您可以(也应该)用sun.miscapache commons Base64替换编码器以获得更好的兼容性。

val b64 = org.apache.commons.codec.binary.Base64.encodeBase64(bytes)
于 2013-02-07T14:51:17.720 回答
0

Here's a simple encoder/decoder I wrote that you can include as source. So, no external dependencies.

The interface is a bit more scala-esque:

import io.github.marklister.base64.Base64._ // Same as Lomig Mégard's answer val b64 = bytes.toBase64

于 2014-03-01T12:54:36.413 回答