1

I want to download some binary data but Chrome forces it to utf-8 which messes up the bytes. If I set href to a data URI and use base64 encoding it works, but I want to avoid that and use a BLOB instead.

Is there a way to stop Chrome from converting this binary data to utf-8?

const data = "\x00\xff\xfe\xe2"
console.log(data)
const file = new Blob([data])

const a = document.getElementById("a")
const url = URL.createObjectURL(file)
a.href = url;
a.download = "test.txt";
<a id="a">Download</a>

In this example, you can see that my string contains the bytes

00 ff fe e2

and I convert that string to a blob. But when you download the file in Chrome and look at the bytes again you'll find

20 c3 bf c3 be c3 a2

instead. What I think is happening is that chrome takes each byte, reads it as utf-16 and converts it to utf-8. For example fe is þ when read as utf-16 but c3 be in utf-8

0

1 Answer 1

3

Strings are implicitly encoded as UTF-8 by the Blob constructor, so pass a typed array instead, such as Uint8Array:

const data = "\x00\xff\xfe\xe2"
console.log(data)
const file = new Blob([Uint8Array.from(data, c => c.charCodeAt(0))])

const a = document.getElementById("a")
const url = URL.createObjectURL(file)
a.href = url;
a.download = "test.txt";
<a id="a">Download</a>

Sign up to request clarification or add additional context in comments.

2 Comments

MDN does mention that DOMStrings are encoded as UTF-8 but I never thought that Blob would reencode the string, since Blobs are used for binary data. What also confused me a lot was that Blob replaces the UTF-16 BOM FE FF with the UTF-8 BOM EF BB BF and ignores existing UTF-8 BOMs. The MIME type also does not matter
@Wendelin blobs are not for the explicit purpose of binary data. Their purpose is to represent files in memory, and that includes plaintext files. The MIME type does not affect encoding, it only affects how other browser APIs choose to interpret the file data when there are multiple options available (e.g. differentiating image/gif and image/png when using a Blob URI as the src of an <img>)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.