简体   繁体   English

将字符串 base64 转换为 Object JS 文件

[英]Convert string base64 to Object JS file

I need to save a JS file in the database and then retrieve this file.我需要在数据库中保存一个 JS 文件,然后检索这个文件。

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)?保存文件并转换为字符串 base64 时,如何读取此 base64 文件并将其转换回原始格式(JS 文件)?

I'm saving to the database with axios like this:我正在使用 axios 保存到数据库中,如下所示:

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:从 base64 数据库检索的文件:

ZXhwb3J0IGRlZmF1bHQgewpsYWJlbDogIlRlc3QgZmlsZSBKUyIsCiAgdmlld0JveDogIjAgMCA4MDAgMTEyMCIsCiAgbG9jYXRpb25zOiBbCiAgICB7CiAgICAgIGlkOiAiMDEiLAogICAgICBwYXRoOgogICAgICAgICJNIDQ0NS43MyA3NDcuNjcgMjA1LjYgNTMzLjQ0IDU3NC4yMiAxIDc5Ny43MyAxOTUuNjMgNzk5IDIwNC43NCA1MzUuNDkgNDkyLjc0IDU5MS44MiA1ODcuMjIgNDQ1LjczIDc0Ny42NyBaIgogICAgfSwKICAgIHsKICAgICAgaWQ6ICIwMiIsCiAgICAgIHBhdGg6ICJNIDEgODE4LjM4IDIwMy4wOCA1MzAuOSA0NDMuMzkgNzQ5Ljc1IDEwNS4yOSAxMTE5LjM4IDEgODE4LjM4IFoiCiAgICB9CiAgXQp9Ow==

Converter here!转换器在这里!

Thank you for your help谢谢您的帮助

In order to decode base64 to string you'll need to use atob .为了将 base64 解码为字符串,您需要使用atob

 const content = atob("ZXhwb3J0IGRlZmF1bHQgewpsYWJlbDogIlRlc3QgZmlsZSBKUyIsCiAgdmlld0JveDogIjAgMCA4MDAgMTEyMCIsCiAgbG9jYXRpb25zOiBbCiAgICB7CiAgICAgIGlkOiAiMDEiLAogICAgICBwYXRoOgogICAgICAgICJNIDQ0NS43MyA3NDcuNjcgMjA1LjYgNTMzLjQ0IDU3NC4yMiAxIDc5Ny43MyAxOTUuNjMgNzk5IDIwNC43NCA1MzUuNDkgNDkyLjc0IDU5MS44MiA1ODcuMjIgNDQ1LjczIDc0Ny42NyBaIgogICAgfSwKICAgIHsKICAgICAgaWQ6ICIwMiIsCiAgICAgIHBhdGg6ICJNIDEgODE4LjM4IDIwMy4wOCA1MzAuOSA0NDMuMzkgNzQ5Ljc1IDEwNS4yOSAxMTE5LjM4IDEgODE4LjM4IFoiCiAgICB9CiAgXQp9Ow=="); console.log(content); const body = document.body; const script = document.getElementById("output"); script.text = content;
 <html> <body> <script id="output" type="text/javascript"></script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM