How to Convert a javascript object to utf-8 Blob for download?

javascript blob to file
javascript blob to string
convert image to blob javascript
byte array to blob javascript
blob in javascript w3schools
how to convert string to utf-8 format in javascript
concatenate blobs javascript
blob to base64

I've been trying to find a solution that works but couldn't find one.

I have an object in javascript and it has some non-english characters in it. I'm trying the following code to convert the object to a blob for download. When I click to download the content, when opening the downloaded JSON the non-English characters are gibberish.

It's a simple object like this one: {name: "שלומית", last: "רעננה"}

function setJSONForDownload(obj) {
    obj = obj || []; // obj is the array of objects with non-english characters
    const length = obj.length;
    if (length) {
      const str = JSON.stringify(obj);
      const data = encode( str );

      const blob = new Blob( [ data ], {
        type: "application/json;charset=utf-8"
     });

      const url = URL.createObjectURL( blob );
      const downloadElem = document.getElementById('download');
      downloadElem.innerText = `Download ${length} pages scraped`;
      downloadElem.setAttribute( 'href', url );
      downloadElem.setAttribute( 'download', 'data.json' );
    }
    else {
      document.getElementById('download').innerText = `No data to download...`;
    }
}

function encode (s) {
  const out = [];
  for ( let i = 0; i < s.length; i++ ) {
    out[i] = s.charCodeAt(i);
  }
  return new Uint8Array(out);
}

Your encode function is broken, as it casts charcodes to bytes. Don't try to implement this yourself, just use the Encoding API:

const str = JSON.stringify(obj);
const bytes = new TextEncoder().encode(str);
const blob = new Blob([bytes], {
    type: "application/json;charset=utf-8"
});

Blob, This behavior is similar to JavaScript strings: we can't change a character in a string, Thanks to type , we can also download/upload Blob objects, and the type That encoding represents binary data as a string of ultra-safe  This returns a Blob instance, which we can then pass to URL.createObjectURL(). To see this in action, I've revamped my previous demo to convert the contents of a Textarea element into a Blob URI which is then made downloadable through the use of the "download" attribute on an anchor tag:

I found a nice block of code that solved my issue. Thanks to 'pascaldekloe' (https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330).

Just changed the encode method to the following:

function encode(s) {
    var i = 0, bytes = new Uint8Array(s.length * 4);
    for (var ci = 0; ci != s.length; ci++) {
        var c = s.charCodeAt(ci);
        if (c < 128) {
            bytes[i++] = c;
            continue;
        }
        if (c < 2048) {
            bytes[i++] = c >> 6 | 192;
        } else {
            if (c > 0xd7ff && c < 0xdc00) {
                if (++ci >= s.length)
                    throw new Error('UTF-8 encode: incomplete surrogate pair');
                var c2 = s.charCodeAt(ci);
                if (c2 < 0xdc00 || c2 > 0xdfff)
                    throw new Error('UTF-8 encode: second surrogate character 0x' + c2.toString(16) + ' at index ' + ci + ' out of range');
                c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
                bytes[i++] = c >> 18 | 240;
                bytes[i++] = c >> 12 & 63 | 128;
            } else bytes[i++] = c >> 12 | 224;
            bytes[i++] = c >> 6 & 63 | 128;
        }
        bytes[i++] = c & 63 | 128;
    }
    return bytes.subarray(0, i);
}

Blob, Firstly we have to convert out configuration object into a Blob : new Blob( [ JSON.stringify(configuration) ], { type: 'text/json;charset=utf-8' } ). The text () method in the Blob interface returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8.

Calling new Blob([DOMString]) will automatically convert your DOMString (UTF-16) to UTF-8.

So all you need is new Blob( [JSON.stringify(obj)] ).

Note that the type won't get used here (it would be only if there was a fetching or if you actually tried to read the Blob), and will anyway only have incidence on how the file might get read (i.e by FileReader.readAsText()), but not on the actual content of the file, so no need to set it.

setJSONForDownload([{ name: "שלומית", last: "רעננה"}]);

function setJSONForDownload(obj) {
  obj = obj || [];
  const length = obj.length;
  if (length) {

    // DOMString
    const str = JSON.stringify(obj);
    // text/plain;UTF-8
    const blob = new Blob([str]);
    
    const url = URL.createObjectURL(blob);
    const downloadElem = document.getElementById('download');
    downloadElem.innerText = `Download ${length} pages scraped`;
    downloadElem.setAttribute('href', url);
    downloadElem.setAttribute('download', 'data.json');
  } else {
    document.getElementById('download').innerText = `No data to download...`;
  }
}
<a id="download">dl</a>

JS Download file on button click in the Browser without a Server, JS: CSV File Creation Using BLOB. jsCSVFileCreationBlob.js. function var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });. if (navigator. Browsers that support HTML5 download attribute. var url = URL. Blob is a fundamental data type in JavaScript. Blob stands for Binary Large Object and it is a representation of bytes of data. Web browsers support the Blob data type for holding data. Blob is the underlying data structure for the File object and the FileReader API. Blob has a specific size and file type just like ordinary files and it can be

JS: CSV File Creation Using BLOB · GitHub, Contribute to eligrey/FileSaver.js development by creating an account on GitHub. Using the application/octet-stream MIME type to force downloads can cause FileSaver saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom }) Note that this is only done if your blob type has charset=utf-8 set. While there’s a mapping for a Blob, the Blob itself resides in the memory. The browser can’t free it. The mapping is automatically cleared on document unload, so Blob objects are freed then. But if an app is long-living, then that doesn’t happen soon. So if we create a URL, that Blob will hang in memory, even if not needed any more.

eligrey/FileSaver.js: An HTML5 saveAs() FileSaver , Text Using Blobs, URL.createObjectURL(), And The Anchor Download Attribute In JavaScript href="**data:**text/plain;charset=utf-8,". I have a javascript object that contains some information. I want to convert this into JSON and download it as a .json file. Seems like I can just to JSON.stringify(obj) to convert it into JSON but

Downloading Text Using Blobs, URL.createObjectURL(), And The , Convert BLOB to Byte Array in Java With an Easy Example. js in which final PDF output But this time it gives me a blob files and saying “can only download as blob if Creates a binary object out of the given string, encoding it as a PDF file. File objects inherit from Blob. In addition to Blob methods and properties, File objects also have name and lastModified properties, plus the internal ability to read from filesystem. We usually get File objects from user input, like <input> or Drag’n’Drop events (ondragend). FileReader objects can read from a file or a blob, in one of

Comments
  • Can you share the data you set in the blob? it's just a text with non-english characters or it's something else?
  • Please look at the link-stackoverflow.com/a/53774151/7849549
  • Return a Uint16Array(). Char codes are 16 bits, not 8. Then make the type "application/json;charset=utf-16" as well.
  • @OriEng it's a simple object like this one: {name: "שלומית", last: "רעננה"}
  • According to your profile image and this simple code I'm sure you're a magician :) Works like a charm, thanks!
  • While it won't be a problem here, because it won't be used, note that even if not per se forbidden, setting the ;charset=nnn will make your MIMEType invalid to some browsers (Safari at least). Better not set it, it doesn't have any incidence whatsoever on the content anyway.
  • And I missed it earlier, but the conversion DOMString to UTF-8 is implicitly done by new Blob([DOMString])
  • @Kaiido Thanks, I had guessed there was something even simpler but didn't take the time to look it up. Have an upvote!
  • thank you , sir . the code is so concise that i used it in my code immediately !