What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?"

HTML

<canvas id="myImage"></canvas> // Canvas loaded with image

Answer №1

Creating a Canvas Image using HTML

<canvas id="myImage"></canvas> // HTML code for loading canvas with an image

Using JavaScript to Save the Image

var can = $("#myImage");
var blob = this.dataURItoBlob(can.toDataURL("image/jpeg"));


var postPromise = $.ajax({
    type: "PUT",
    url: 'URL_to_save_the_image',//API URL for saving the image
    data: blob, // The data is sent without being transformed into a query string
    processData: false, // Important step to avoid "jquery.js:8453 Uncaught TypeError: Illegal invocation" error caused by transformation to query string
    contentType: 'image/jpeg'
});
postPromise.done(function(data, textStatus, jqXHR) {
    //Code for handling success goes here
});

postPromise.fail(function(jqXHR, textStatus, errorThrown) {
    //Code for handling failure goes here
});

function dataURItoBlob(dataURI) {
    // Function to convert base64/URLEncoded data component to raw binary data in a string format
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);
    // Separating the mime component from the data URI
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    // Writing the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {
        type: mimeString
    });
}

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

The conflict arises when importing between baseUrl and node_modules

I am currently working on a TypeScript project with a specific configuration setup. The partial contents of my tsconfig.json file are as follows: { "compilerOptions": { "module": "commonjs", "baseUrl": &quo ...

Attention: The index value is not defined:

This is the main page with a date picker that links to index.php, where the data table is located. Everything works fine when I select a date, but if I make any changes on the index.php page or try to access it directly, I encounter this error: Notice: ...

Steps to refresh my View following an Ajax Post request

Working in an MVC environment, I find myself calling a Controller method from my View. The Controller method conducts some validation checks and then returns to the same view with a faulty modelstate. However, despite expecting all of my validation fields ...

Tips for periodically updating an asp.net mvc view using signalR?

Currently, I am using periodic Ajax calls from the view to fetch new data every 2 seconds. The controller is responsible for monitoring hardware/sensor signals. Is it possible to implement SignalR instead of Ajax? I have come across examples where change ...

Unable to alter the dimensions of the `symbol` element from an external SVG using CSS, although the other `symbol` within the same document is responsive to styling changes

Could someone help me find the bug in my code related to resizing SVG symbols with CSS? I am able to resize one <symbol> from an external SVG file, but not another <symbol> from the same file. In my CSS, I am trying to change the width and hei ...

How to Automatically Close an Ajax Modal Popup After Executing Code in ItemCommand in ASP.Net

I am currently facing an issue with closing a ModalPopup after a code sequence is executed. The situation at hand involves coding a filebrowser for the company and everything seems to be working fine except for the downloading of files. I have implemented ...

Is it possible to employ a method to eliminate a specific valuable element 'this' from an array?

I am working on a task management app that allows users to create a To-Do list and remove specific items from the list. Currently, I am facing an issue with using 'localStorage' to save the list when the page is refreshed. The problem arises when ...

Next.js allows for dynamic page routing using the `useState` hook to redirect users

In my Next.js project, I am using the useState hook to render different components based on the button a user clicks. The main page, called account.js in the application, contains the following code: // Importing react and getting components import React f ...

The implementation of $(this).addClass within AJAX success is not yielding the desired results

Currently, I am working on some ajax processing for a click event. Everything is functioning correctly so far, but now I have encountered an issue when trying to add a class in the success function. I am using $(this).addClass("cover");, however, nothing ...

What is the best way to add indentation to HTML code in a code tag?

Looking to insert some Python code into an HTML document using the code tag. Here is an example: <code> for iris, species in zip(irises, classification): if species == 0: print(f'Flower {iris} is Iris-setosa') </ ...

Adjust color scheme of drop-down menu

Having trouble changing the background color for my drop down menu. I tried to change the color for the sub div but it's not working. Can anyone help me fix this issue? Here is the code snippet: http://jsfiddle.net/3VBQ6/4/ #nav li:hover ul.sub li { ...

Issue encountered in loading css and js folders during the build of the Angular2 application due to the files not being found

I have developed an Angular 2 application that utilizes Node.js server APIs. After building the app using nd b, the files were generated in the dist folder. Where should I specify the production URL for the build so that all CSS and JS files load properly? ...

The PhoneGap integration causing issues with jQuery Slide Panel functionality

My code runs smoothly in browsers, but faces issues with PhoneGap compilation. The SCROLL FROM LEFT/SCROLL FROM RIGHT functionality doesn't seem to work as expected. Despite this, the LEFT/RIGHT menus can be accessed by clicking the button at the top ...

Cease the use of bi-directional data binding on an Angular directive

One way I've been attempting to send information to a directive is through the following setup: <ui-message data="{{app}}"></ui-message> In my controller, this is how I define it: app.controller("testCtrl", function($scope) { $scope.a ...

What could be the reason behind the success of my API call in Chrome while encountering failure when implemented in my

I'm attempting to access the Binance API in order to obtain the current price of Litecoin (LTC) in Bitcoin (BTC). For this purpose, I have tested the following URL on my web browser: "https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC". Now, I ...

The list does not get updated through the Ajax call until another request is made to the server

I am currently facing an issue with my ajax call that updates a kendo multiselect's data source based on another dropdown selection. The multiselect also has a read action that filters the data. AJAX Call function getPsychiatrists() { return $.aj ...

The functionality of jQuery touch events on iOS devices is not functioning properly

I'm encountering issues with jQuery touch events on iOS devices. Here is my current script: $(document).ready(function(){ var iX = 0,iY = 0,fX = 0,fY = 0; document.addEventListener('touchstart', function(e) { ...

Ensuring the website retains the user's chosen theme upon reloading

I have been developing a ToDo App using MongoDB, EJS, and Node JS. My current challenge involves implementing a theme changer button that successfully changes colors when clicked. However, whenever a new item is added to the database, the page reloads caus ...

Maintain the image's aspect ratio by setting the width equal to the height when the height is

I am uncertain if achieving this purely with CSS is possible, but it would be ideal. I currently have an image: <img src="#" class="article-thumb"> CSS: .article-thumb { height: 55%; } Is there a way to set the width equal to the height? My g ...

When there is an absence of data, the jQuery datatable mysteriously van

I have encountered an issue in my Django app where a datatable used in the template disappears if there is missing data in any column or row. The problem occurs when trying to download the data in CSV, Excel, PDF, or copy format. Here is the HTML code snip ...