Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

javascript - 如何在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?

(我在做什么错以及如何解决?)

  ask by Toufique Imam translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...