Skip to content

Commit 93b95be

Browse files
committed
Introduced a simple way to work with files inside frontend
The usecase of this code is something like this: let image that user is making a protonmail or any another application where 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 convert any `Array[Byte]` from frontend to URL as simple call `FileService.asURL`, create an anchor to download it as `FileService.asAnchor` and asynchronously convert any uploaded `File` to `Array[Byte]` as `FileService.asBytesArray`, or to `InputStream` via `FileService.asInputStream`. 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. `FileService.asInputStream` is using `FileReaderSync` that is also missed inside scala-js-dom. I've opened a PR: scala-js/scala-js-dom#424 but it might be a while. Also, this is draft API but it is supported by majority of modern browsers: https://developer.mozilla.org/en-US/docs/Web/API/FileReaderSync#Browser_Compatibility
1 parent a834c72 commit 93b95be

File tree

3 files changed

+143
-2
lines changed

3 files changed

+143
-2
lines changed
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
package io.udash.utils
2+
3+
import java.io.{IOException, InputStream}
4+
5+
import org.scalajs.dom._
6+
import org.scalajs.dom.html.Anchor
7+
import org.scalajs.dom.raw.Blob
8+
import scalatags.JsDom
9+
10+
import scala.scalajs.js
11+
import scala.concurrent.{Future, Promise}
12+
import scala.scalajs.js.annotation.JSGlobal
13+
import scala.scalajs.js.typedarray.ArrayBuffer
14+
import scala.util.Try
15+
16+
@js.native
17+
@JSGlobal
18+
sealed class FileReaderSync() extends js.Object {
19+
def readAsArrayBuffer(blob: Blob): ArrayBuffer = js.native
20+
}
21+
22+
sealed class FileBufferedInputStream(val file: File) extends InputStream {
23+
val fileReaderSync = new FileReaderSync()
24+
25+
var filePos: Int = 0
26+
var pos: Int = 0
27+
28+
var buffer: Array[Byte] = Array.empty
29+
30+
override def read(): Int = {
31+
if (pos >= buffer.length) {
32+
import js.typedarray._
33+
34+
if (filePos >= file.size) {
35+
return -1
36+
}
37+
38+
val len = math.min(filePos + 1024, file.size.toInt)
39+
val slice = file.slice(filePos, len)
40+
buffer = new Int8Array(fileReaderSync.readAsArrayBuffer(slice)).toArray
41+
filePos += buffer.length
42+
pos = 0
43+
}
44+
val r = buffer(pos).toInt & 0xff
45+
pos += 1
46+
r
47+
}
48+
}
49+
50+
object FileService {
51+
52+
final val OctetStreamType = "application/octet-stream"
53+
54+
/**
55+
* Converts specified bytes array to string that contains URL
56+
* that representing the array given in the parameter with optionally specified mime-type.
57+
*
58+
* Keep in mind that returned URL should be revoked via `org.scalajs.dom.revokeObjectURL(url)`.
59+
*/
60+
def asURL(bytes: Array[Byte], mimeType: String = OctetStreamType): String = {
61+
import js.typedarray._
62+
63+
val jsBytes = js.Array[js.Any](bytes.toTypedArray)
64+
val blob = new Blob(jsBytes, BlobPropertyBag(mimeType))
65+
URL.createObjectURL(blob)
66+
}
67+
68+
/**
69+
* Create an anchor element that on click downloads byte array as a file with specified name.
70+
*
71+
* Keep in mind that anchor's href URL should be revoked via `org.scalajs.dom.revokeObjectURL(url)`.
72+
*/
73+
def asAnchor(filename: String, bytes: Array[Byte], mimeType: String = OctetStreamType): JsDom.TypedTag[Anchor] = {
74+
import JsDom.all._
75+
76+
val download = attr("download")
77+
a(href := asURL(bytes, mimeType), download := filename)
78+
}
79+
80+
/**
81+
* Asynchronously convert specified file to bytes array.
82+
*/
83+
def asBytesArray(file: File): Future[Array[Byte]] = {
84+
import js.typedarray._
85+
86+
val fileReader = new FileReader()
87+
val promise = Promise[Array[Byte]]()
88+
89+
fileReader.onerror = (e: Event) =>
90+
promise.failure(new IOException(e.toString))
91+
92+
fileReader.onabort = (e: Event) =>
93+
promise.failure(new IOException(e.toString))
94+
95+
fileReader.onload = (_: UIEvent) =>
96+
promise.complete(Try(
97+
new Int8Array(fileReader.result.asInstanceOf[ArrayBuffer]).toArray
98+
))
99+
100+
fileReader.readAsArrayBuffer(file)
101+
102+
promise.future
103+
}
104+
105+
/**
106+
* Convert specified file to InputStream with blocking I/O
107+
*
108+
* Because it is using synchronous I/O that could potentially this API can be used only inside worker.
109+
*
110+
* This method is using FileReaderSync that is part of Working Draft File API.
111+
* Anyway it is supported for majority of modern browsers
112+
*/
113+
def asInputStream(file: File): InputStream =
114+
new FileBufferedInputStream(file)
115+
}

guide/guide/.js/src/main/scala/io/udash/web/guide/views/frontend/FrontendFilesView.scala

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ class FrontendFilesView extends View {
2424
),
2525
p("You can find a working demo application in the ", a(href := References.UdashFilesDemoRepo, target := "_blank")("Udash Demos"), " repositiory."),
2626
h3("Frontend forms"),
27+
p(i("FileService"), " is an object that allows to convert ", i("Array[Byte]")," to URL, save it as file from frontend ",
28+
" and asynchronously convert ", i("File"), " to ", i("Array[Byte]"), "."),
2729
p(i("FileInput"), " is the file HTML input wrapper providing a property containing selected files. "),
2830
fileInputSnippet,
2931
p("Take a look at the following live demo:"),

guide/guide/.js/src/main/scala/io/udash/web/guide/views/frontend/demos/FileInputDemo.scala

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package io.udash.web.guide.views.frontend.demos
22

33
import io.udash.css.CssView
4+
import io.udash.utils.FileService
45
import io.udash.web.guide.demos.AutoDemo
56
import io.udash.web.guide.styles.partials.GuideStyles
67
import scalatags.JsDom.all._
@@ -9,8 +10,11 @@ object FileInputDemo extends AutoDemo with CssView {
910

1011
private val (rendered, source) = {
1112
import io.udash._
12-
import org.scalajs.dom.File
13+
import org.scalajs.dom.{File, URL}
1314
import scalatags.JsDom.all._
15+
import org.scalajs.dom.window
16+
17+
import scala.concurrent.ExecutionContext.Implicits.global
1418

1519
val acceptMultipleFiles = Property(true)
1620
val selectedFiles = SeqProperty.blank[File]
@@ -19,7 +23,27 @@ object FileInputDemo extends AutoDemo with CssView {
1923
FileInput(selectedFiles, acceptMultipleFiles)("files"),
2024
h4("Selected files"),
2125
ul(repeat(selectedFiles)(file => {
22-
li(file.get.name).render
26+
val content = Property(Array.empty[Byte])
27+
28+
window.setTimeout(() =>
29+
FileService.asBytesArray(file.get) foreach { bytes =>
30+
content.set(bytes)
31+
}, 3000)
32+
33+
val name = file.get.name
34+
li(showIfElse(content.transform(_.isEmpty))(
35+
span(name).render,
36+
{
37+
val anchor = FileService.asAnchor(name, content.get)(name).render
38+
39+
window.setTimeout(() => {
40+
content.set(Array.empty[Byte])
41+
URL.revokeObjectURL(anchor.href)
42+
}, 10000)
43+
44+
anchor
45+
}
46+
)).render
2347
}))
2448
)
2549
}.withSourceCode

0 commit comments

Comments
 (0)