What is the appropriate content-type to use when sending AJAX POST data?

Having an issue sending base64 image data using ajax post. I suspect the problem lies with the Content-Type value, as I have tried using application/json, text/json, and image/jpeg without success.

Javascript

function sendFormData(fD)
{
    var urls = fD.get('urls');
    console.log('urls', urls);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/editsongs.update_artwork');
    alert(urls);
    xhr.setRequestHeader("Content-type", "image/jpeg");
    xhr.send(urls);
}

The browser console displays:

["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExMWFhUXGRgbGBgXGR0aGRgXHRgYFx4YGxkYHiogGh4lGxgdIjEhJSkrLi4uGh8zODMtNygtLisBCgoKDg0OGhAQGy0lHSUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIANEA8QMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAA…

Java Server code

public String updateArtwork(Request request, Response response)
{
    System.out.println("Received artwork");

    for(String s:request.queryParams())
    {
        System.out.println("---"+s);
    }
    System.out.println("ReadParms");
    return "";
}

Outputs from the server are:

Received artwork
ReadParms

Updated to Send as Form Instead

// Once we got everything, time to retrieve our objects
function sendData()
{
    var fD = new FormData();

    // Send Files data directly
    var files = imgList.filter(
        function isFile(obj)
        {
            return obj.type === 'file';
        }
    );

    files.forEach(
        function appendToFD(obj)
        {
            fD.append('files[]', obj.file);
        }
    );

    // For elems, we will need to grab the data from the server
    var elems = imgList.filter(
        function isElem(obj)
        {
            return obj.type === "element";
        }
    );

    var urls = elems.map(
        function grabURL(obj)
        {
            return obj.element.src;
        }
    );

    if (urls.length)
        fD.append('urls', JSON.stringify(urls));

    sendFormData(fD);
};

function sendFormData(fD)
{
    // But here we will just log the formData's content
    var files = fD.getAll('files[]');
    console.log('files: ', files);
    var urls = fD.get('urls');
    console.log('urls', urls);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/editsongs.update_artwork');
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(fD);
}

Then on the server side:

public String updateArtwork(Request request, Response response)
{
    System.out.println("Received artwork");

    for(String s:request.queryParams())
    {
        System.out.println("***"+s);
        System.out.println(request.queryParams(s));
    }
    System.out.println("ReadParms");
    return "";
}

Outputs from the server are:

Received artwork
***-----------------------------330219842643
Content-Disposition: form-data; name
"urls"

["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMSEhUSExIWFhUXFxgXGBcYFRgXFxkdGBcWGBgYFx0YHSggHR0lHRkYITEhJSkrLi4uFyA1ODMtNygtLisBCgoKDg0OFQ8PFSsZF..."]
-----------------------------330219842643--

ReadParms

I'm now able to receive the data, but I am unsure how to parse the Content-Disposition part in Java.

This code was not originally written by me, hence the construction of FormData does not come from an actual form. My initial attempt was to try extracting from FormData and sending it in a different way. An alternative approach would be to avoid storing in FormData initially, but I am uncertain how to do this.

Update 2

Tried sending only the first URL instead of formdata or an array of URLs, as there is only ever one URL. However, it did not work as nothing was received by the server.

function sendFormData(urls)
{
    console.log('urls', urls[0]);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/editsongs.update_artwork');
    xhr.setRequestHeader("Content-type", "text/json");
    alert(JSON.stringify(urls[0]));
    xhr.send(JSON.stringify(urls[0]));
}

Answer â„–1

To access information from the URL, utilize queryParams() to retrieve query parameters.

If you need to extract data from the request body, use body().

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

What is the best approach to creating DOM elements in AngularJS?

My controller contains data with various actions and different numbers of parameters: $scope.actions = [ {name : 'rotate', r : '30'}, {name : 'translate', x : '10', y : '10'}, {name : 'scale', ...

Acquire the model from a field within an Angular Formly wrapper

I'm in the process of designing a wrapper that will exhibit the model value as regular text on the page. Once the mouse hovers over this text, it transforms into a Formly field, which works perfectly fine. However, I'm encountering an issue where ...

leveraging embedded jetty for developing a web-based interface

As a newcomer to web development and using embedded Jetty, I have created the source code below in Eclipse IDE. I need to programmatically start the Jetty server and cannot use the command line to do so. The web interface must be lightweight due to the li ...

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

Error code 0 occurs in jQuery AJAX when there is an issue with the communication between the client

Currently delving into the world of ASP.NET and wanted to create a basic website utilizing ajax to retrieve a simple string from the server. Upon running the ajax request, an error message pops up stating An error occurred: 0 error Here's a glimpse ...

the absence of any content being shown when using v-else

I'm currently delving into Vue.js and stumbled upon an unusual behavior that I couldn't find any information about on the Internet. For some reason, the DIV with v-else isn't rendering any content that I place inside it. I tried to underst ...

What is the best way to utilize the existing MUI state in order to calculate and show column totals?

I am currently in the process of developing an MUI web application to keep track of some personal data. Within this application, I have incorporated the MUI datagrid pro component to efficiently display the data with its robust filtering capabilities. In ...

Is it possible to create a hyperlink on the second page that directs to the first page and triggers a specific JavaScript function on the first page?

Working with a former colleague's code in C#, asp.net MVC, Telerik/Kendo controls. I am trying to navigate to a specific section on a page from another page that uses tabs/sections with links at the top of the page to toggle visibility based on the se ...

Is there a way to implement retry functionality with a delay in RxJs without resorting to the outdated retryWhen method?

I'd like to implement a retry mechanism for an observable chain with a delay of 2 seconds. While researching, I found some solutions using retryWhen. However, it appears that retryWhen is deprecated and I prefer not to use it. The retry with delay s ...

Guide on transferring data from a component to App.vue in Vue 3, even with a router-view in the mix

I have the following layout: src components Footer.vue views Page.vue App.vue I want to access the 'message' vari ...

Adjusting canvas size to match content dimensions

I posed a similar inquiry and it was categorized as a duplicate even though the suggested duplicate did not provide an answer to my question. Edit: The purported duplicate was [stackoverflow.com/questions/17211920/make-canvas-height-auto][1] I am utilizi ...

The term 'undefined' does not refer to an object

My div contains the following code: <em id="ProductPrice" class="ProductPrice VariationProductPrice">$75.00</em> I want to change the text color if the value changes. This is what I tried: <script> $(document).ajaxSuccess(function(){ ...

Is it within the realm of possibility for a route-handling function to accept more than two parameters?

Recently, I started learning about node js and delved into the world of jwt authentication. While going through some code snippets, I came across a request handler in express that caught my attention. app.post('/login',function(req,res){...}); ...

Building a React.js application and fetching information with Ajax

In my quest to create a high-speed React.js application that functions as a game, I find myself in need of displaying real-time data. However, the traditional method of loading this data from the server using Ajax doesn't quite align with the reactive ...

Tips for integrating Series data into Highcharts using MVC

Looking at this JFiddle demonstration of Highcharts http://jsfiddle.net/yxz80f4u/9/ We can observe the data being inserted as [Date.UTC(YYYY,MM,DD,HH,MM,SS), Y-data-point] data: [ [Date.UTC(1970, 7, 5,1,1,1), 2.22], [Date.UTC(1 ...

What is causing the error message "Uncaught TypeError: Cannot read properties of null (reading 'push')" to be displayed when running this code?

I encountered an issue while trying to run this code which resulted in an Uncaught TypeError: Cannot read properties of null (reading 'push') console.log("HI"); let addbtn = document.getElementById("addbtn"); addbtn.addEventLi ...

Unable to create account using PHP

Every time I attempt to create an account, the data I receive is always problematic. The username must be between 3 and 15 characters I find it frustrating that the account creation never goes through successfully. What baffles me even more is that af ...

What is the best way to generate a multitude of diverse arrays?

For my hash table project, I am looking to create an array with 8000 random integers ranging from 0 to 65535. I am familiar with the math.random function, but I am unsure how to generate random numbers within such a wide range. Any tips or suggestions wo ...

Creating an Edit and Delete feature for a looped textbox in JavaScript

Exploring the realm of web development, I am on a mission to integrate an add/edit/delete feature to manipulate form values using Javascript. Let me shed some light on what I aim to achieve. Within my codebase, there exists a loop that sequentially displa ...

Testing the functionality of Vaadin Textfield using Selenium

In Vaadin, I have implemented a save button and a textfield where the state of the save button (enabled/disabled) is linked to the input in the textfield using a ValueChangeListener. The save button should be disabled when the textfield is empty and enable ...