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

Nuxt.js static pages with relative URLs

I am currently working on developing static pages with Nuxt.js (MPA). After executing the generate command, I noticed that all the URLs in the <nuxt-link> tag start from the root directory, specifically /. For instance, my project structure looks lik ...

generate dynamic custom headers in an express application for accessibility by an Angular application

https://i.stack.imgur.com/6jyNE.pngRecently, I have started using Express and despite my extensive research, I haven't been able to find a solution to my issue. The problem is that I am receiving headers in my Express app, but when I attempt to make t ...

Automatically choose radio buttons within an li element in a loop

Hey there, I'm new to SO and this is my first question. As a bit of a newbie, I found this jquery code snippet on another SO answer that I want to use. The function I'm aiming for is the same, but the markup structure in my HTML is different bec ...

Activate the "order evaluation" trigger on the checkout page in Woocommerce

I have implemented the Woocommerce Advanced Shipping plugin created by Jeroen Sormani for managing shipping methods, along with the WooCommerce Pay for Payment plugin developed by Karolína Vyskočilová to add a fixed €5 fee to the "cash on delivery" pa ...

Tips for managing several Material UI Slide Components at once

Utilizing Material UI's Slide component, I have encountered an issue with my code. Upon hovering over a card, I intend for an individual slide to appear. However, the current implementation causes both slides to be displayed when hovering over any of ...

Provide a unique <li> attribute for the JavaScript function to utilize

Is there a way to pass specific attributes from dropdown options to a javascript function? I have tried using .data() and .attr(), but the console keeps showing "undefined". Any suggestions on how to achieve this in a cleaner and simpler way would be gre ...

What are the alternatives to using Node.js for implementing real-time chat functionality in core PHP using socket.io?

I am in the process of integrating socket.io into my core PHP custom framework. I prefer not to use node.js because it may cause conflicts with my existing AJAX code. 1) Is there a way to use socket.io without relying on node.js? 2) If node.js is necessar ...

How can I utilize jQuery to add tags in a box?

I have an idea for a feature similar to the Stack Overflow tag insert. My goal is to have a box where I can type in a tag, click 'Add', and see it appear above. Additionally, I want this action to update an array called 'SelectedTags'. ...

This particular JavaScript function is only designed to operate on the initial input box in the provided

I have a question regarding echoing rows of $data inside input boxes. I am using a JavaScript function that is supposed to copy the input value to the clipboard when the input box is clicked. However, I am encountering an issue - the function only works ...

Setting up a CentOs Linux environment to host and run a node.js server

Just installed node.js on my new VPS server. I have written a basic script called "server.js" and it is currently running on port 8080. The location of the script is in the "var/www/html/" directory. However, whenever I try to access my domain, it only dis ...

When retrieving data from a JSON file, only display the value instead of showing the entire

When a user tries to login, I have created a modal window. If the user enters incorrect credentials, it returns SignInStatus.Failure, which is fine. However, the page then refreshes and only displays the number "3" at the top of the page with no other cont ...

An easy way to attach a Contextmenu to a specific element

I have implemented a scrolling feature for one of the div elements in my Application. Inside this div, there is a templated table with over 100 rows. Users are able to add or delete rows using a contextMenu. The contextMenu offers 4 options - AddTop, AddB ...

How come using a query object as a parameter for .limit() returns an empty array?

I am currently working on a mongoose query setup where I have a custom queryObject containing key-value pairs for specific records. If a key-value pair does not exist in the req.query, it is omitted from the queryObject. Oddly enough, when setting the que ...

Create a dynamic animation effect for the placeholder in an input field that triggers when the user starts typing

Have you ever come across interactive demos like this one? I've noticed that most examples involve creating a new element. parent().append("<span>" + $input.attr('placeholder') + "</span>"); Is there a way to make the placehol ...

What is the best way to add Vue dependency using CDN?

For my project which is built using Kendo, Vue, .Net, Angular and jQuery, I need to incorporate https://www.npmjs.com/package/vue2-daterange-picker. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Incorporating a new function into a TypeScript (JavaScript) class method

Is it possible to add a method to a method within a class? class MyClass { public foo(text: string): string { return text + ' FOO!' } // Looking for a way to dynamically add the method `bar` to `foo`. } const obj = new MyCl ...

What can I do to resolve a node server issue with the error message "npm ERR! code ELIFECYCLE npm ERR! errno 1"?

npm ERROR! code ELIFECYCLE npm ERROR! errno 1 npm ERROR! [email protected] start: node server npm ERROR! Exit status 1 npm ERROR! npm ERROR! Task failed at the [email protected] start script. npm ERROR! This may not necessarily be an ...

Easier JavaScript for numerous HTML elements

I am an aspiring JavaScript learner seeking advice. Currently, I am working on a website that features numerous items with multiple images for each. I am utilizing JQuery to display a larger image when the user hovers over a thumbnail image. My query is ...

Nginx deployment of React causes issues with AJAX Axios functionality

I am interested in integrating frontend with backend on cloud virtual machines such as DigitalOcean, AWS, or Microsoft Azure. Frontend: React Backend: Spring Spring MVC Mybatis + Tomcat (Excluding Spring Boot) After researching various methods using N ...

Querying cookies using Jquery/Ajax

Is there a way to trigger an ajax call when a page detects the presence of a cookie? I'm having trouble getting the ajax call to work in the code below. Any assistance would be greatly appreciated. EDIT: I have updated the code and it is now function ...