Pass (Send) BASE64 string to server side using jQuery AJAX in ASP.Net

Last Reply 2 months ago By pandeyism

Posted 2 months ago

Hi Team,

I am uploading an excel and sending the data as base64string to Webmethod in ajax call, but I am getting 400 bad request.

If i send as a regular string then no issue but if I send as base64 string then getting 400 error. Could anyone help me on this?

Note:

1)If data is normal string no issue, but I need base64 string only

2) File type should be excel only

3) I tried stringfy but no luck

Thanks in Advance.

You are viewing reply posted by: pandeyism 2 months ago.
Posted 2 months ago

Hi bebins,

Refer below sample.

HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        var fileName;
        $("input[type=file]").change(function (e) {
            var file = e.target.files[0];
            fileName = e.target.files[0].name;
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#hfBase64').val(e.target.result);
            }
            if (file) {
                reader.readAsDataURL(file);
            }
        });
        $("#btnUpload").on("click", function () {
            var base64 = $("#hfBase64").val();
            var obj = {};
            obj.data = base64;
            obj.name = fileName;
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/UploadFile',
                data: JSON.stringify(obj),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json', error: function (e) { debugger; }
            });
        });
    });
</script>
<div>
    <asp:HiddenField ID="hfBase64" runat="server" />
    <asp:FileUpload ID="FileUpload1" runat="server" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
    <asp:Button Text="Upload" runat="server" ID="btnUpload" />
</div>

Namespaces

C#

using System.Web.Services;

VB.Net

Imports System.Web.Services

Code

C#

[WebMethod]
public static void UploadFile(string data, string name)
{
    string base64 = data.Replace("data:application/vnd.ms-excel;base64,", "")
        .Replace("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,", "");
    // Saving Base64 string as file.
    System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/Files/" + name), Convert.FromBase64String(base64));
}

VB.Net

<WebMethod()>
Public Shared Sub UploadFile(ByVal data As String, ByVal name As String)
    Dim base64 As String = data.Replace("data:application/vnd.ms-excel;base64,", "").Replace("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,", "")
    ' Saving Base64 string as file.
    System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/Files/" & name), Convert.FromBase64String(base64))
End Sub