Performing a Javascript ajax post of a canvas snapshot in "image/jpeg" format to an asp.net web form

Here is the JavaScript AJAX code snippet:

var dataURL = canvas.toDataURL("image/jpeg");
var xhr = new XMLHttpRequest();
xhr.open("POST", "myPage.aspx", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function () {
        if (xhr.readyState != 4) return;
        if (xhr.status != 200) {
            alert("Status: " + xhr.status);
        } else {
            alert(xhr.responseText);
        }
    };

xhr.send("imgData=" + dataURL);

This is the C# server-side code within myPage.aspx's page load event:

// enctype="multipart/form-data"
string img = Server.UrlDecode(Request.Form["imgData"]);

img = Regex.Match(img, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
//img = img.Replace("data:image/png;base64,", "");
img = img.Trim('\0');
//byte[] bytes = Encoding.UTF8.GetBytes(img);
byte[] bytes = Convert.FromBase64String(img);

An error is consistently being raised by the last block of server-side code... It appears to be related to a base64 conversion issue... "System.FormatException: 'Invalid length for a Base-64 char array or string.'" Any suggestions on how to resolve this? Thank you.

Answer №1

Upon conducting tests and experiments, it was determined that the issue lay in the javascript encoding... the correct code is:

xhr.send("imgData=" + encodeURIComponent(dataURL));

Appreciate all the assistance :-)

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

Why does jQuery only execute the very first condition or none at all if the first condition is false?

I'm trying to create a fixed button that, when clicked, scrolls to a specific section on the page. However, only the first condition seems to be working, and the other conditions are being ignored even when the first one is false. Can you help me figu ...

What is the process for placing API routes within the new app directory of Next.js?

If you have a test API located at: pages\api\accounts\login.js, and are currently exploring the new app folder, which is still in its experimental phase in Next.js (as of today). Are you wondering if it's feasible to transfer your logi ...

Retrieve information from the index resource using AJAX

I feel like I might be overcomplicating things, but basically, I'm trying to retrieve all the data from an index resource and have it load when a button is clicked using AJAX. I've been using a serializer to tidy up the JSON. Both "/categories" ...

Is there a way to determine if an npm package is compatible with ES6 import syntax for importing?

Aside from reviewing the documentation of the package and trying different methods through trial and error, how can one be certain if an npm package can be imported using the ES6 import syntax? Is there a specific file within the package folder that can b ...

jQuery - Wait for the completion of one UI change before initiating another UI change

Is there a way to implement the functionality where $("#login").toggle("drop", {direction: "left"}); is executed first and upon completion, $("#register").toggle("drop", {direction: "right"}); is then carried out? The issue arises from the fact that the ...

Utilizing AJAX to determine if a specific phrase includes the queried terms

Currently, I am working on an AJAX search bar. At the moment, it only allows me to search for exact words in my table. ID|Skillset|Description| 1|game|i love game 2|photography|i love to take photo 3|game|game is my forte My current query searches for ex ...

storing audio files locally with Vue.js

Looking for a way to store a sound locally for my Battleship game rather than referencing it on the internet. Here's the code that triggers the sound: @click.prevent="fireSound('http://soundbible.com/grab.php?id=1794&type=mp3')" I atte ...

Unlock the potential of JavaScript by accessing the local variable values in different functions

I've been struggling for days to find a solution to this issue... https://i.stack.imgur.com/KDN7T.jpg https://i.stack.imgur.com/tOfCl.jpg The image above illustrates the challenge I'm facing - trying to apply data values from elsewhere to the ...

What could be the reason I am unable to choose data properties from the dropdown options?

There are two different dropdowns for clothing types and colors. When a type of clothing is selected from the first dropdown, JSON data will fill the second dropdown with options based on the first dropdown selection. After selecting an option from the se ...

Developing Vue applications with dynamic component insertion

Looking to develop a user-friendly form builder using Vue, where users can easily add different form fields by clicking buttons from a menu. If I only had one type of form field to add, it could be done like this (https://jsfiddle.net/u6j1uc3u/32/): <d ...

Error 403 with Google Search Console API: Access Denied

Currently, I am attempting to extract data from the GSC Search Analytics API using Python. Despite diligently following this resource, I have encountered an error that persists despite multiple attempts to remedy it: raise HttpError(resp, content, uri=se ...

Using `on('click') in JQuery has a one-time effect

Although there are many questions similar to this one, I am still having trouble figuring it out. <div class="message"></div> <button id="getMessage">Get Quote</button> $.getJSON("http://quotesondesign.com/wp-json/posts?filter[or ...

Exploring Best Practices for Coding in node.js

Method 1: Constructor and Prototype Objects function Database(url) { this.url = url; } Database.prototype.info = function (callback) { http.get(this.url + '/info', callback); }; Method 2: Closures Approach function Database(url) { ...

Managing spinners in Protractor when they are concealed by a wrapper element

While writing a test for an Angular app using Protractor, I encountered several issues with handling spinners. I managed to solve some of them, but I'm unsure how to test spinners that are hidden by a wrapper. For instance, when the parent tag has ng- ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

Looking for a bootstrap table code that includes checkboxes and a save button, so that when the save button is clicked, it

Seeking a Bootstrap table code that includes row checkboxes. When the save button is clicked, it should return the selected checkbox rows. ...

Issue with Initiating Html5Qrcode Scanner Automatically Following Form Submission

I'm currently utilizing the Html5Qrcode scanner within a WordPress plugin to scan barcodes for products. My workflow involves: 1. Initiating the Html5Qrcode scanner and scanning a barcode. 2. Using the decoded barcode value to search for and display ...

Adjust the pagination length within the jQuery DataTables plug-in

I am looking to customize the pagination length in DataTables plug-in for jQuery. Specifically, I want to calculate the number of pages on the server side and display the correct amount of buttons on the client side. Can anyone provide guidance on how to ...

How to effectively combine css() and delay() in jQuery?

fid: https://jsfiddle.net/k13sazuz/ Is there a way to create a delay chain for CSS rules using jQuery? $('.two').css('background','blue').delay(11800).css('background','red'); ...

Merge various categories into a single entity

I am encountering a challenge where I need to create an object from multiple types and return it to the front end. Here is the scenario I am aiming for (Using C#). The format that the front end requires looks like this { ... "props" : // this is where I ...