utils.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. export function dataURItoBlob(dataURI) {
  2. // convert base64 to raw binary data held in a string
  3. // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
  4. var byteString = atob(dataURI.split(",")[1]);
  5. // separate out the mime component
  6. var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
  7. // write the bytes of the string to an ArrayBuffer
  8. var ab = new ArrayBuffer(byteString.length);
  9. // create a view into the buffer
  10. var ia = new Uint8Array(ab);
  11. // set the bytes of the buffer to the correct values
  12. for (var i = 0; i < byteString.length; i++) {
  13. ia[i] = byteString.charCodeAt(i);
  14. }
  15. // write the ArrayBuffer to a blob, and you're done
  16. var blob = new Blob([ab], { type: mimeString });
  17. return blob;
  18. }
  19. export const saveFile = function (strData, filename) {
  20. var link = document.createElement("a");
  21. if (typeof link.download === "string") {
  22. document.body.appendChild(link); //Firefox requires the link to be in the body
  23. link.download = filename;
  24. link.href = strData;
  25. link.click();
  26. document.body.removeChild(link); //remove the link when done
  27. } else {
  28. location.replace(uri);
  29. }
  30. };