Unable to transfer Base64 encoded data to C# through AJAX

I'm facing an issue where a base64 string I send through ajax to an aspx page with C# code behind always arrives empty. Despite other form fields posting successfully, this particular string is not making it through.

The base64 string in question appears as follows:

QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw==

The method responsible for sending the string to the C# code behind reads:

string signature = Request.Form.Get("newsig");
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap, signature);

Within the C# code, the handling of the base64 string occurs like so:

string base64image = sig;
// Convert base64string to byte array
var newbytes = Convert.FromBase64String(base64image);

I suspect that the length of the base64 string might be causing issues at times. Is there a more efficient way to manage base64 strings in C#?

UPDATE: Below is an excerpt from my ajax post method:

var localbase64string = localStorage["signature"];
var b64 = localbase64string.replace(/^data:image\/(png|jpg);base64,/, "");

var formData = new FormData($(this)[0]);
formData.append( 'newsig', b64);

var sendPost = 'http://xxx.xx/this.aspx';

$.ajax({
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    timeout: 50000,
    url: sendPost,
    success: function(data){
        alert('Sent!');
        window.location.href = './../mainmenu.html';
        
   }, error:function (){  
                alert("something went wrong!");
	}
});

Answer №1

To ensure the content you are sending, you can also utilize Request.Content.ReadAsStringAsync().Result within your C# receiving method.

Take a look at this example I quickly assembled:

C#:

public IHttpActionResult PostB64Test(string one, string two)
    {
        string b64 = Request.Content.ReadAsStringAsync().Result;            
        return Ok();
    }

JS:

// Here's an instance url where I'm appending the base64 string to the POST body,
// and other parameters in the query string.

 var url = '/api/xxx/b64/?one=' +1 +'&two=' +2 +'';

 var b64 = ""; // Your specific base64 string for example "9j/4AAQSkZJRgABAg..."
 $http.post(url, { b64: b64 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble navigating back to the homepage

Recently, I started following a tutorial on YouTube to create a basic frontend in React with Bootstrap. However, I encountered a roadblock while trying to implement a specific functionality. The issue stemmed from the fact that react-router-dom v6 no lon ...

What is the best way to record data while initiating a process in node.js?

In my latest project, I have implemented a function that spawns a process and requires logging specific information to the console. Here is an example of how this function is structured: function processData(number) { var fileName = settings.file || "de ...

JQuery validation for phone number format 01x-xxxxxxxx

Currently, I am using jQuery Validate to validate the form. In order to validate the phone number field, I have implemented the following code: The phone number should be written in the format 01x-xxxxxxxx var phonereg = /^[0-9]{3}\-[0-9]{7}$/; H ...

What is the method for updating the content within a div element?

I am trying to add multiple elements to my content, including an h1 element, an input field, and some buttons. I have written a function to create the h1 and input elements, but when trying to add them to my content div, I encountered an error (TypeError ...

What can be done to stop the event handler from executing?

My goal is to verify a user's authentication every time they click on a button. If the user happens to be logged out and tries to click on a button, they should be redirected back to the home page. The issue I'm facing is that the code after the ...

"What is the best way to include additional fields within a popover in an AngularJS application

This is my code for implementing a popover using AngularJS. I am trying to figure out how to add custom styling to the popover HTML, but I am having trouble binding elements in that part of the code. <!DOCTYPE html> <html> <head> <l ...

Trouble with bringing in the solana/web3.js library

After successfully importing the solana/web3.js package and running it within a NodeJS file, everything was working fine. However, things took a turn when attempting to connect this file with basic HTML, resulting in an error being thrown. import { Tra ...

While iterating over the key with a variable in a loop, only one property is displayed consistently instead of four different

Currently, I am working on creating an address book using JavaScript. The problem I am facing is that the properties of my objects are not providing me with the necessary information. I need 4 different properties instead of 4 loops with the same property. ...

Ways to adjust the size of div and its elements to fit the window dimensions

When resizing the window, the banner image shrinks while the header and header items remain the same size. However, there is an issue when the header takes up around 30% of the screen in phone view. Here is the CSS code I am using: .headerdiv{ width: ...

Could you explain the purpose of the usage section in a CodeMirror 6 language pack?

When you visit (for example) https://github.com/exercism/codemirror-lang-elixir?tab=readme-ov-file, you will see the following code snippet: import { StreamLanguage } from '@codemirror/language' import { elixir } from 'codemirror-lang-elixir ...

How do I navigate back to show the initial parent component instead of the nested child component in ReactJS?

The data flow in my React app goes like this: SubmitForm -parent-> Results -parent-> Presentation -parent-> ButtonBackToSearch I am delving into ReactJS and trying to adopt the right mindset for creating single-page applications. Currently, I am ...

What is the best way to extract "true" values from an array and store them in a new array during iteration?

I am currently enrolled in a Codecademy course and I am facing a roadblock. My main goal is to gain a solid grasp of JavaScript. The current task at hand is as follows: "There is an array of unnecessary words. Your goal is to iterate over the array and fi ...

Place a call directly from the webpage

Is there a way to initiate a phone call using JavaScript? I've tried the code below: document.location.href = "tel:15555551212" While this code takes me to the dial screen of the mobile application, I actually want to place the call directly. Any ...

Retrieve the identification number from the code snippet containing the "append(<tr><td="ID">..." template

I have a table that I'm populating with data from a firebase database using the append() function. $("#table_body").append("<tr><td>" + name + "</td>" + "<td>" + brand + "</td>" + ...

Having trouble with my JQuery image slider... Can anyone help troubleshoot what I might have missed?

I am trying to create a simple image slider, but it doesn't seem to be working. I followed a tutorial on YouTube closely, but since I can't compare my code with theirs on a website, I'm having trouble identifying the mistake. Despite followi ...

Utilize jQuery to seamlessly transfer each recorded audio file from rows to corresponding input fields within the table

I have a table below with 2 rows but it can be doubled with a button (Add another Word media) and only one submit button for all rows: <tbody> <tr class="form-row dynamic-medias" id="medias-0"> <td class=&quo ...

What could be the reason for the lack of rendering in this imported React component using System.import?

I've been experimenting with dynamic code splitting using webpack 2 and react. As part of my testing, I decided to create a component that fetches code asynchronously: import React, { Component } from 'react' export class Async extends Com ...

How can JavaScript be utilized to disable the use of the spacebar?

I have implemented a live search feature on the website I'm working on. Currently, the search function queries the MySql database as soon as the first character is entered and updates the results with each subsequent character input. However, I'v ...

Combine the array elements by date in Angular, ensuring no duplicates are present

How can array data be merged based on the date while avoiding duplicates? See the code snippet below: [ { date: [ '2019-12-02 08:00:00', '2019-12-03 08:00:00' ], upload:["47.93", "47.46", "47.40", "47.29" ], download: ["43.90", ...

I seem to be experiencing a depletion of my cache... (Objects are mysteriously disappearing from my cache)

Currently in the process of developing a website using ASP.NET Webforms.. I've implemented caching strategically with High / Normal / Low priority levels, specifying durations of 2 weeks, 1 week, and 4 hours respectively. To aid in debugging, I disp ...