0

I have a blob image in the client side (javascript) and i want to convert it to base64 string. Then, pass it to code behind (C#).

I used the following code for converting the blob to base64 string:

 var reader = new FileReader();
                reader.onload = function (event) {
                    createImage(event.target.result); //event.target.results contains the base64 code to create the image.
                };
                reader.readAsDataURL(blob);//Convert the blob from clipboard to base64

I tried to display the reader object to see how my base64 string looks like. I have got this [object FileReader].

I want to extract the base 64 string from it, how to do so??

user3054453
  • 55
  • 1
  • 1
  • 6
  • 1
    I think this can be useful to you when you mentioning javascript convert to base64 https://stackoverflow.com/questions/246801/how-can-you-encode-a-string-to-base64-in-javascript – Nezir Sep 29 '18 at 06:08
  • 1
    also this info can be useful when you want to decode to c# base 64 https://stackoverflow.com/questions/7134837/how-do-i-decode-a-base64-encoded-string – Nezir Sep 29 '18 at 06:09

1 Answers1

1

The simple way of coding/decoding to base64 in javascript:

var str ="some sample js to code";
function utoa(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
}
console.log("CODED: "+utoa(str));


function atou(str) {
    return decodeURIComponent(escape(window.atob(str)));
}
console.log("DECODED: "+atou(utoa(str)));

Here is also code for code and decode string in c#:

//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string encodedString = Base64Encode("sample of text in c#");

            Console.WriteLine("CODEE:" + encodedString);
             Console.WriteLine("DECODEE:" + Base64Decode(encodedString));
        }
        public static string Base64Encode(string plainText) {
          var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
          return System.Convert.ToBase64String(plainTextBytes);
        }
        public static string Base64Decode(string base64EncodedData) {
          var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
          return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }
    }
}
Nezir
  • 6,727
  • 12
  • 54
  • 78