Skip to content

Commit e92d4bc

Browse files
committed
Introduced a simple way to save any bytes array as file from frontend
The usecase of this code is something like this: let image that user is making a protonmail or any another application that content inside frontend (=browser storage) some secret user's data that shouldn't be exposed to backend. Secret key for example or anything like that. This code allows to developer to save any `Array[Byte]` from frontend without hacks and question because creating a blob isn't clean. Unfortunately scalatags doesn't support `download` attribute and I need to make it by hand. I've opened a PR: com-lihaoyi/scalatags#212 to introduce it, but it might be a while until it is included to release.
1 parent 7e54db1 commit e92d4bc

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package io.udash.utils
2+
3+
import org.scalajs.dom.document
4+
import org.scalajs.dom.raw._
5+
import scalatags.JsDom.all._
6+
7+
import scala.scalajs.js
8+
import js.JSConverters._
9+
import js.typedarray._
10+
11+
object FileDownload {
12+
def save(filename: String, bytes: Array[Byte], mimeType: String = "application/octet-stream"): Unit = {
13+
val jsBytes = Array[js.Any](bytes.toTypedArray).toJSArray
14+
val blob = new Blob(jsBytes, BlobPropertyBag(mimeType))
15+
val url = URL.createObjectURL(blob)
16+
val download = attr("download")
17+
val anchor = a(href := url, download := filename, style := "display: none")(filename).render
18+
document.body.appendChild(anchor)
19+
anchor.click()
20+
document.body.removeChild(anchor)
21+
URL.revokeObjectURL(url)
22+
}
23+
}

0 commit comments

Comments
 (0)