0

I need to save a JS file in the database and then retrieve this file.

When saving the file and converting to string base64, how do I read this base64 file and convert it back to the original format (JS file)?

I'm saving to the database with axios like this:

let formData = new FormData();
formData.append('file', file);
const create = (formData, onUploadProgress) => {
  return http.post(
    '/api/v1/maps/upload',
    formData,
    {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress,
    }
  );
};

Original file:

export default {
label: "Test file JS",
  viewBox: "0 0 800 1120",
  locations: [
    {
      id: "01",
      path:
        "M 445.73 747.67 205.6 533.44 574.22 1 797.73 195.63 799 204.74 535.49 492.74 591.82 587.22 445.73 747.67 Z"
    },
    {
      id: "02",
      path: "M 1 818.38 203.08 530.9 443.39 749.75 105.29 1119.38 1 818.38 Z"
    }
  ]
};

File retrieved from base64 database:

ZXhwb3J0IGRlZmF1bHQgewpsYWJlbDogIlRlc3QgZmlsZSBKUyIsCiAgdmlld0JveDogIjAgMCA4MDAgMTEyMCIsCiAgbG9jYXRpb25zOiBbCiAgICB7CiAgICAgIGlkOiAiMDEiLAogICAgICBwYXRoOgogICAgICAgICJNIDQ0NS43MyA3NDcuNjcgMjA1LjYgNTMzLjQ0IDU3NC4yMiAxIDc5Ny43MyAxOTUuNjMgNzk5IDIwNC43NCA1MzUuNDkgNDkyLjc0IDU5MS44MiA1ODcuMjIgNDQ1LjczIDc0Ny42NyBaIgogICAgfSwKICAgIHsKICAgICAgaWQ6ICIwMiIsCiAgICAgIHBhdGg6ICJNIDEgODE4LjM4IDIwMy4wOCA1MzAuOSA0NDMuMzkgNzQ5Ljc1IDEwNS4yOSAxMTE5LjM4IDEgODE4LjM4IFoiCiAgICB9CiAgXQp9Ow==

Converter here!

Thank you for your help

1 Answer 1

2

In order to decode base64 to string you'll need to use atob.

<html>

<body>
  <script id="output" type="module"></script>
  <script type="module">
    const content = atob("ZXhwb3J0IGRlZmF1bHQgewpsYWJlbDogIlRlc3QgZmlsZSBKUyIsCiAgdmlld0JveDogIjAgMCA4MDAgMTEyMCIsCiAgbG9jYXRpb25zOiBbCiAgICB7CiAgICAgIGlkOiAiMDEiLAogICAgICBwYXRoOgogICAgICAgICJNIDQ0NS43MyA3NDcuNjcgMjA1LjYgNTMzLjQ0IDU3NC4yMiAxIDc5Ny43MyAxOTUuNjMgNzk5IDIwNC43NCA1MzUuNDkgNDkyLjc0IDU5MS44MiA1ODcuMjIgNDQ1LjczIDc0Ny42NyBaIgogICAgfSwKICAgIHsKICAgICAgaWQ6ICIwMiIsCiAgICAgIHBhdGg6ICJNIDEgODE4LjM4IDIwMy4wOCA1MzAuOSA0NDMuMzkgNzQ5Ljc1IDEwNS4yOSAxMTE5LjM4IDEgODE4LjM4IFoiCiAgICB9CiAgXQp9Ow==");
    
    console.log(content);
    const body = document.body;
    const script = document.getElementById("output");
    script.text = content;
    script.src = "content.js";
    
    //import * as example from "./content.js";
    //console.log(example.locations);
  </script>
</body>

</html>

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

2 Comments

Thanks for the feedback, but atob doesn't work, as you can see in the Sandbox ( codesandbox.io/s/cranky-surf-unoef?file=/src/App.js ), I need to convert it back to an object and the atob convert to text
@CleitondeFreitas Added an adjustment. The content is now appended back to an existing script tag.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.