Hi! I am getting a Base64 encoded file (through AP...
# javascript
m
Hi! I am getting a Base64 encoded file (through API) from a ktor server from a compose for web application. The encoded string arrives well on the web but when I convert it to a Blob I guess something is not working since the file is not readable anymore (xlsx file). Here is the code that converts ByteArray to Blob
Copy code
fun bytesToFile(byteArray: ByteArray){
    val blob = Blob(byteArray.toTypedArray(), BlobPropertyBag("application/vnd.ms-excel"))
    val link = document.createElement("a") as HTMLAnchorElement
    link.href = URL.Companion.createObjectURL(blob)
    link.download = "test.xlsx"
    link.click()
    //document.removeChild(link)
}
Any idea what it might be wrong?
b
Did you decode base64 string before converting it to byte array? I suspect you're trying to convert still base 64 encoded representation of your file to blob
m
sure I did, using ktor lib internal Api like this:
return base64String.body().decodeBase64Bytes()
. I did a unit test on the Java side with the decode/encode base64 functions and they do work. I am quite new on the web/js world so excuse my ignorance and many thanks!
Ok, after some debugging it seems that the bytes are correctly transformed. The only problem is that the actual file has the bytes transformed to int, like in a text file. Here is an example:
8075342008880-61-115-718400
. A normal file, decoded with xxd looks like this:
504b 0304 1400 0808 0800 a789 b954 0000 PK...........T..
They are the same values only integers.
I finally solved it by using the fetch API like this:
Copy code
fun bytesToFile(data: String) {
    val link = document.createElement("a") as HTMLAnchorElement
    val dataUrl = "data:octet/stream;base64,$data"
    fetch(dataUrl).then {
        it.blob().then {
            val urlBlob = js("URL.createObjectURL(it)")
            link.href = urlBlob
            link.download = "new_test.xlsx"
            link.click()
        }
    }
}
Maybe not the most elegant way but it works! 🙂
168 Views