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??

2

1 Answer 1

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.