简体   繁体   English

如何在javascript中正确解码base64字符串

[英]How to decode a base64 string properly in javascript

I tried to convert a base64 string generated from pdf file using FileReader.readAsDataURL() to its original format.我尝试将使用FileReader.readAsDataURL()从 pdf 文件生成的 base64 字符串转换为其原始格式。
In NodeJS I did it like this and it was able generated the pdf to its initial state.在 NodeJS 中,我是这样做的,它能够将 pdf 生成到其初始状态。

filebuffer = "data:application/pdf;base64,JVBERi0xLjQKJSDi48/..........."
let base64file = fileBuffer.split(';base64,').pop();
fs.writeFileSync('download.pdf',base64file,{encoding:'base64'},function(err){
    if(err === null){
        console.log("file created");
        return;
    }
    else{
        console.log(err);
        return;
    }
})

But i tried to do it in HTML + Javascript in this way .But in this way , pdf was empty/no letter wasn't in it但我试图以这种方式在 HTML + Javascript 中做到这一点。但是这样,pdf 是空的/没有字母不在其中

let stringval = "data:application/pdf;base64,JVBERi0xLjQKJSDi48/..........."
let encodedString = stringval.split(';base64,').pop();

let data = atob(encodedString);
let blob = new Blob([data]);

// //if you need a literal File object
let file = new File([blob], "filename");

link.href = URL.createObjectURL(file);
link.download = 'filename';

I was Capturing file and converting to base64 string in this way:我正在以这种方式捕获文件并转换为 base64 字符串:

captureFile: function () {
event.preventDefault();
const file = event.target.files[0];
$("#labelinput1").html(file.name);
const reader = new window.FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
  var x = reader.result.toString();
  App.buffer2 = x;
  console.log("buffer", App.buffer);
};}

Then after clicking a button , I added the buffer to IPFS node然后单击按钮后,我将缓冲区添加到 IPFS 节点

addfile: async function () {
if (App.buffer2 === null) return;
App.node = await window.Ipfs.create()
App.node.add(App.buffer2, function (errx, resipfs) {
      if (errx === null) {
        console.log(resipfs[0].hash);
        App.buffer2 = null;
        return App.showInfo(resipfs[0].hash);
      }
      else {
        return App.showError(errx.message.toString() + errx.stack.toString());
      }
    });
}

using the IPFS HASH i can get back the base64 encoded string , I retrieved this string in this way:使用 IPFS HASH 我可以取回 base64 编码的字符串,我以这种方式检索了这个字符串:

ipfsfiledownload: async function () {
var filebuffer = await App.node.cat(hashtext);
var stringval = filebuffer.toString();
//convert this string to main file
}

I used Truffle Petshop and write those functions in top of it.我使用了Truffle Petshop并在其上编写了这些函数。 Here is a IPFS hash QmfSefUiwjV44hpfnHyUngGATyHm9M4vN3PzF1mpe59Nn1 .这是一个 IPFS 哈希QmfSefUiwjV44hpfnHyUngGATyHm9M4vN3PzF1mpe59Nn1 you can try out this Hash value in nodejs with this code您可以使用此代码在 nodejs 中尝试此哈希值

const IPFS = require('ipfs');
const fs = require('fs');
const main = async() => {
    const node = await IPFS.create()
    var fileBuffer = await 
    node.cat('QmfSefUiwjV44hpfnHyUngGATyHm9M4vN3PzF1mpe59Nn1')
    fileBuffer = fileBuffer.toString()
    let base64file = fileBuffer.split(';base64,').pop();
    fs.writeFileSync('download.pdf',base64file, {encoding:'base64'},function(err){
        if(err === null){
            console.log("file created");
            return;
        }
        else{
            console.log(err);
            return;
        }
    })
}

main()

You can find the full code here .您可以在此处找到完整代码。 What I am doing wrong and how to solve it?我做错了什么以及如何解决?

After converting the base64 string using atob() , I converted it to Uint8Array Then created the blob and file .使用atob()转换base64 string后,我将其转换为Uint8Array然后创建 blob 和 file 。 It seems to work now ..现在似乎可以工作了..

Here is the full code :这是完整的代码:

ipfsfiledownload: async function () {
    var hashtext = document.getElementById("id_ipfshash").value //getting the IPFS HASH
    var link = document.getElementById("downloadLink"); 
    if (hashtext === null) return
    var filebuffer = await App.node.cat(hashtext); //getting the base64 string from IPFS
    var stringval = filebuffer.toString();

    console.log(stringval);
    let encodedString = stringval.split(',')[1]; //getting the base64 hash
    let mimetype = stringval.split(',')[0].split(':')[1].split(';')[0]; //getting the mime type

    let data = atob(encodedString); //ascii to binary
    var ab = new ArrayBuffer(data.length); 
    var ia = new Uint8Array(ab);
    //converting to Uint8Array
    for(var i = 0;i<data.length;i++){
          ia[i] = data.charCodeAt(i);
    }
    let blob = new Blob([ia],{ "type": mimetype});
    let filename = 'filename.' + App.getExtension(mimetype);
    let file = new File([blob], filename);

    link.href = window.URL.createObjectURL(file);
    link.download = filename;
    link.click();
}

Try below code snippet. 请尝试以下代码段。 Go through the example I think you should be able to find the mistakes you made. 通过示例,我认为您应该能够发现自己犯的错误。

 var data = atob( 'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' + 'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' + 'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' + 'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' + 'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' + 'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' + 'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' + 'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' + 'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' + 'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' + 'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' + 'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' + 'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G'); let blob = new Blob([data]); let file = new File([blob],"hello.pdf") var url = window.URL.createObjectURL(file); var link = document.createElement("a"); document.body.appendChild(link); link.style = "display: none"; link.href = url; link.download = "hello.pdf" link.click(); window.URL.revokeObjectURL(url); link.remove(); 

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

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