Skip to content

Commit d950c0c

Browse files
committed
FileService: a way to work with file at 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 `Seq[Array[Byte]]` from frontend to URL as simple call `FileService.createURL`, asynchronously convert any uploaded `File` to `Array[Byte]` as `FileService.asBytesArray`, or to `InputStream` via `FileService.asInputStream` inside worker. Unfortunately scalatags doesn't support `download` attribute and I need to make it by hand. I've opened a PR[^1] 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[^2] but it might be a while. Also, this draft API but it is supported by majority of modern browsers[^3]. [^1]: com-lihaoyi/scalatags#212 [^2]: scala-js/scala-js-dom#424 [^3]: https://caniuse.com/?search=FileReaderSync
1 parent 6aacd3f commit d950c0c

File tree

3 files changed

+184
-1
lines changed

3 files changed

+184
-1
lines changed
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
package io.udash.utils
2+
3+
import com.avsystem.commons.misc.AbstractCase
4+
5+
import java.io.{IOException, InputStream}
6+
import org.scalajs.dom._
7+
import org.scalajs.dom.raw.Blob
8+
9+
import scala.scalajs.js
10+
import scala.concurrent.{Future, Promise}
11+
import scala.scalajs.js.annotation.JSGlobal
12+
import scala.scalajs.js.typedarray.ArrayBuffer
13+
import scala.util.Try
14+
15+
@js.native
16+
@JSGlobal
17+
private final class FileReaderSync() extends js.Object {
18+
def readAsArrayBuffer(blob: Blob): ArrayBuffer = js.native
19+
}
20+
21+
final class FileBufferedInputStream(file: File, bufferSize: Int) extends InputStream {
22+
val fileReaderSync = new FileReaderSync()
23+
24+
var filePos: Int = 0
25+
var pos: Int = 0
26+
27+
var buffer: Array[Byte] = Array.empty
28+
29+
override def available(): Int = {
30+
val res = file.size.toInt - filePos
31+
if (res < 0) 0 else res
32+
}
33+
34+
override def read(): Int = {
35+
if (pos >= buffer.length) {
36+
import js.typedarray._
37+
38+
if (filePos >= file.size)
39+
return -1
40+
41+
val len = math.min(filePos + bufferSize, file.size.toInt)
42+
val slice = file.slice(filePos, len)
43+
buffer = new Int8Array(fileReaderSync.readAsArrayBuffer(slice)).toArray
44+
filePos += buffer.length
45+
pos = 0
46+
}
47+
val r = buffer(pos).toInt & 0xff
48+
pos += 1
49+
r
50+
}
51+
52+
override def close(): Unit = filePos = file.size.toInt
53+
54+
override def markSupported(): Boolean = true
55+
56+
var markPos: Option[Int] = None
57+
58+
override def mark(readlimit: Int): Unit =
59+
markPos = Some(pos + filePos - buffer.length)
60+
61+
override def reset(): Unit = markPos match {
62+
case Some(p) =>
63+
filePos = p
64+
pos = 0
65+
buffer = Array.empty
66+
markPos = None
67+
68+
case _ =>
69+
// do nothing
70+
}
71+
}
72+
73+
final case class CloseableUrl(value: String) extends AbstractCase with AutoCloseable {
74+
override def close(): Unit = {
75+
URL.revokeObjectURL(value)
76+
}
77+
}
78+
79+
object FileService {
80+
81+
final val OctetStreamType = "application/octet-stream"
82+
83+
/**
84+
* Converts specified bytes arrays to string that contains URL
85+
* that representing the array given in the parameter with specified mime-type.
86+
*
87+
* Keep in mind that returned URL should be closed.
88+
*/
89+
def createURL(bytesArrays: Seq[Array[Byte]], mimeType: String): CloseableUrl = {
90+
import js.typedarray._
91+
92+
val jsBytesArrays = js.Array[js.Any](bytesArrays.map(_.toTypedArray) :_ *)
93+
val blob = new Blob(jsBytesArrays, BlobPropertyBag(mimeType))
94+
CloseableUrl(URL.createObjectURL(blob))
95+
}
96+
97+
/**
98+
* Converts specified bytes arrays to string that contains URL
99+
* that representing the array given in the parameter with `application/octet-stream` mime-type.
100+
*
101+
* Keep in mind that returned URL should be closed.
102+
*/
103+
def createURL(bytesArrays: Seq[Array[Byte]]): CloseableUrl =
104+
createURL(bytesArrays, OctetStreamType)
105+
106+
/**
107+
* Converts specified bytes array to string that contains URL
108+
* that representing the array given in the parameter with specified mime-type.
109+
*
110+
* Keep in mind that returned URL should be closed.
111+
*/
112+
def createURL(byteArray: Array[Byte], mimeType: String): CloseableUrl =
113+
createURL(Seq(byteArray), mimeType)
114+
115+
/**
116+
* Converts specified bytes array to string that contains URL
117+
* that representing the array given in the parameter with `application/octet-stream` mime-type.
118+
*
119+
* Keep in mind that returned URL should be closed.
120+
*/
121+
def createURL(byteArray: Array[Byte]): CloseableUrl =
122+
createURL(Seq(byteArray), OctetStreamType)
123+
124+
/**
125+
* Asynchronously convert specified file to bytes array.
126+
*/
127+
def asBytesArray(file: File): Future[Array[Byte]] = {
128+
import js.typedarray._
129+
130+
val fileReader = new FileReader()
131+
val promise = Promise[Array[Byte]]()
132+
133+
fileReader.onerror = (e: Event) =>
134+
promise.failure(new IOException(e.toString))
135+
136+
fileReader.onabort = (e: Event) =>
137+
promise.failure(new IOException(e.toString))
138+
139+
fileReader.onload = (_: UIEvent) =>
140+
promise.complete(Try(
141+
new Int8Array(fileReader.result.asInstanceOf[ArrayBuffer]).toArray
142+
))
143+
144+
fileReader.readAsArrayBuffer(file)
145+
146+
promise.future
147+
}
148+
149+
/**
150+
* Convert specified file to InputStream with blocking I/O
151+
*
152+
* Because it is using synchronous I/O that could potentially this API can be used only inside worker.
153+
*
154+
* This method is using FileReaderSync that is part of Working Draft File API.
155+
* Anyway it is supported for majority of modern browsers
156+
*/
157+
def asInputStream(file: File, bufferSize: Int = 1024): InputStream =
158+
new FileBufferedInputStream(file, bufferSize)
159+
}

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: 23 additions & 1 deletion
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._
@@ -12,14 +13,35 @@ object FileInputDemo extends AutoDemo with CssView {
1213
import org.scalajs.dom.File
1314
import scalatags.JsDom.all._
1415

16+
import scala.concurrent.ExecutionContext.Implicits.global
17+
1518
val acceptMultipleFiles = Property(true)
1619
val selectedFiles = SeqProperty.blank[File]
1720

1821
div(
1922
FileInput(selectedFiles, acceptMultipleFiles)("files"),
2023
h4("Selected files"),
2124
ul(repeat(selectedFiles)(file => {
22-
li(file.get.name).render
25+
val content = Property(Array.empty[Byte])
26+
27+
FileService.asBytesArray(file.get) foreach { bytes =>
28+
content.set(bytes)
29+
}
30+
31+
val name = file.get.name
32+
li(showIfElse(content.transform(_.isEmpty))(
33+
span(name).render,
34+
{
35+
val url = FileService.createURL(content.get)
36+
val download = a(href := url.value, attr("download") := name)(name)
37+
val revoke = a(href := "#", onclick := { () =>
38+
content.set(Array.empty[Byte])
39+
url.close()
40+
})("revoke")
41+
42+
Seq(download, span(" or "), revoke).render
43+
}
44+
)).render
2345
}))
2446
)
2547
}.withSourceCode

0 commit comments

Comments
 (0)