简体   繁体   中英

Converting base64 encoded bytes to string different in Javascript and C#

I have an image & when I convert to Base64 using JavaScript and C# , it gives me two different values. what is the reason for this?

JavaScript Code

  function LoadSvg() {
            var main = document.getElementById('svgimg');
            var data = main.innerHTML;
            debugger;
            var base64blob = Base64.encode(data);
            alert(base64blob);
            var image2 = document.getElementById('Img2');
            image2.src = 'data:image/svg+xml;base64,' + base64blob;
        }

C# code

string val=litSvg.Text;
byte[] arr = Encoding.UTF8.GetBytes(val);
string toBaseVal = Convert.ToBase64String(arr);      
ExternalHtml = 
   "<img id=\"dfs\" src=\"data:image/svg+xml;base64," + toBaseVal + "\" />";

in JavaScript main value and c# val values are same. how this happens? if I need to same same value in java script out put, how can I do that?

Edit :

val value :

<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='470px' height='310px'><line x1='40' y1='10' x2='40' y2='250'style='stroke: rgb(0,0,0); stroke-width: 1' />...

main value :

 <svg id="svg-code" xmlns="http://www.w3.org/2000/svg" version="1.1" width="470px" height="310px"> <line x1="40" y1="10" x2="40" y2="250" style="stroke: rgb(0,0,0); stroke-width: 1"></line>

O/P values :

base64blob : CiAgICAgICAgICAgICAgICA8.....

toBaseVal : PHN2ZyB4bWxucz0naHR0cDov ....

The problem is spaces here.

Remove leading and trailing spaces from your svg file. In addition - remove all excesive whitespace too ie. collapse 1+ whitespace to one whitespace and in your C# - read+convert your file like this:

byte[] arr = System.IO.File.ReadAllBytes(svf_file);
string toBaseVal = Convert.ToBase64String(arr);

Leave encodings alone.

One code calculates base64 with excesive spaces and the other without (as it removes them implicitly) - read innerHTML

Your Javascript decoded buffer contains whitespace at the beginning

LINEFEED SPACE SPACE SPACE < ...


$ echo "CiAgICAgICAgICAgICAgICA8" | base64 -d | hexdump -C -n 32
00000000  0a 20 20 20 20 20 20 20  20 20 20 20 20 20 20 20  |.               |
00000010  20 3c                                             | <| 

Your C# decoded buffer is correct

$ echo "PHN2ZyB4bWxucz0naHR0cDov" | base64 -d | hexdump -C -n 16
00000000  3c 73 76 67 20 78 6d 6c  6e 73 3d 27 68 74 74 70  |<svg xmlns='http|
00000010

It is possible that they will both give the desired result though

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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