Transmit a byte array from an AJAX request to Java

I am attempting to use AJAX to send a byte array to the server:

$.ajax({
  url: armd.scieldan.server + "/detachedSignFile/",
  timeout: 120000,
  type: "POST",
  data: byteArray,
  responseType: 'arraybuffer',
  success: function(response) {
    console.log("Sign: " + response);
  },
  error: function() {
    console.log("error");
  }
});

However, when trying to extract that array from httpExchange, the content of requestBody appears to be empty:

public void handle(HttpExchange httpExchange) throws IOException {
    httpExchange.getResponseHeaders().set("Content-Type", "text/plain");

    InputStream requestBody = httpExchange.getRequestBody();

    byte[] receivedBytes = IOUtils.toByteArray(requestBody);
}

https://i.sstatic.net/0txFz.png

It seems that a BufferedInputStream is present inside the requestBody, but I am unable to access it. Is there a way to properly pass the byte array through JSON to HttpExchange?

Answer №1

When utilizing AJAX on the client side and HTTP/REST on the server, the content is typically treated as string data unless specified otherwise with special handling.

An effective way to enhance this process, especially for smaller content and less strict performance requirements, is to encode the bytes in base-64 and transmit them as the payload using text/plain as the request content type. On the server side, the input stream can be read entirely and decoded or wrapped in a base-64 decoder.

Alternatively, sending the data with a binary content type like application/octet-stream (unless dealing with a specific file type) allows the network infrastructure to properly handle the transmitted bytes from the client to the server.

If the content type is not explicitly defined and defaults to something like text/plain or application/json, it may encounter issues when encountering an invalid sequence of bytes like a null character instead of the expected ASCII encoding. This interruption in processing the input stream can lead to loss of data input, resulting in no information being reported to the server.

Answer №2

I encountered an issue where I overlooked the fact that my initial AJAX request was sending the "OPTIONS" HTTP method, indicating it needed to be treated as a preflight request. To address this, I made some modifications to the server-side code:

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
    httpExchange.getResponseHeaders().add("Access-Control-Max-Age", "600");
    httpExchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
    httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "*");

    byte[] cms = null;
    int statusCode;

    if (httpExchange.getRequestMethod().equals("OPTIONS")) {
        OutputStream responseBody = httpExchange.getResponseBody();
        httpExchange.getResponseHeaders().add("Content-Type", "text/plain");
        httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "*");
        httpExchange.sendResponseHeaders(204, 0);
        responseBody.flush();
        responseBody.close();
        return;
    }
    Map parameters = (Map) httpExchange.getAttribute("parameters");
    byte[] receivedBytes = IOUtils.toByteArray(parameters.get("data").toString());
   
    //other logic and response
}

As a result of processing a request with the "OPTIONS" method, AJAX now automatically sends a proper "POST" request.

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

Requests in Node.js may unexpectedly stall and remain unresolved until the server is restarted

I've encountered a strange and seemingly sporadic issue with our web application that I can't seem to resolve through debugging. The app runs smoothly for varying durations, ranging from 10 minutes to 6 hours, but then all of a sudden, any remote ...

What is the best way to store a collection of objects generated from an AJAX request that retrieves information from a JSON file using JavaScript?

I have successfully retrieved my JSON objects using the code snippet below. After logging the variable "value2", I can confirm that the values are being displayed in my console. However, I am encountering an issue where my "arraytest" remains empty even af ...

Save room for text that shows up on its own

I am currently dealing with a situation where text appears conditionally and when it does, it causes the rest of the page to be pushed down. Does anyone know the best way to reserve the space for this text even when it's not visible so that I can pre ...

Display the information in real-time as it is being transmitted to the backend

I'm facing a challenge with the user experience. Currently, I am developing a chat application using Ionic, Angular, and Firebase. The issue at hand is that messages are only displayed once they are successfully sent to the server. This means that o ...

What is the best way to create a time sequence canvas player?

Currently, I am working on a JavaScript feature that involves displaying a player's path on top of a static map. I have a sequence of timestamps and x,y coordinates, and I am searching for a library that can use this information to create a video play ...

Is there a way to determine the bounding rectangle of a specific word within a paragraph when you only have its index?

I am currently developing a text-to-speech functionality for a react application that can emphasize the word being spoken by highlighting it with a background color. This feature closely resembles the layout of the Firefox reader view. However, my curren ...

Tips for refreshing an altered row in DataTables

When trying to edit a row in a Datatable with data loading from the database, a popup appears after clicking on the row. However, after editing the field and clicking on the submit button, it does not update. An error code 403 (Forbidden) is shown in the ...

Using Ext JS to send an AJAX request with a JSON object to an ASP.NET MVC web application

Currently, I am attempting to transmit a json object (extjs client) to an asp.net server-side application: Here is the sample request with logic intact: var orderData = []; for (i = 0; i < checkedList.length; i++) { orderData.push ...

Is there a way to sort through a JSON object using JavaScript?

I have a JSON string that looks like this: { "Animal":{ "Cat":20, "Dog":10, "Fish":5 }, "Food":{ "Pizza":500, "Burger":200, "Salad" ...

Encountering an Uncaught TypeError in Reactjs: The property 'groupsData' of null is not readable

While working on a ReactJs component, I encountered an issue with two basic ajax calls to different APIs. Even though I am sure that the URLs are functioning and returning data, I keep getting the following error message: Uncaught TypeError: Cannot read p ...

What are the steps to get an Angular.js application ready for deployment on Heroku?

I recently created an Angular.js quiz application by following a tutorial video. Although the app is functional on Mozilla Developer Edition, I have encountered issues with other browsers when running it locally. The root directory of my app includes the ...

Update a servlet's element value and send the updated data back to the webpage seamlessly using AJAX without the need for a refresh

I'm working on a project involving a web page and a servlet. I've successfully created dynamic input elements using JavaScript in the webpage, which are then used to pass data to the backend servlet for mathematical calculations. The IDs of these ...

Issue with localStorage.getItem preventing the navbar styling from being updated

Currently, I'm working on a website using Bootstrap and I am incorporating both light and dark themes. Everything seems to be functioning well except for one issue - when the page is refreshed, the browser doesn't retain the theme that was previo ...

SelectionList values and display options

I'm currently utilizing jquery to populate a dropdown list in ASP.NET MVC $(function () { $.getJSON('/GetFoo', function (result) { var ddl = $('#foo'); ddl.empty(); $(result).each(function () { ...

Click event in Django does not attach to the div element

I've been attempting to attach a click event to a div element within an html file in a Django project. The code snippet for my menu.html is as below: {% extends "base.html" %} {% block title %}Today's menu{% endblock %} {% block head %} &l ...

Handling 'Bad Request' error with AJAX in CodeIgniter

Operating on Windows 10 with Codeigniter 3 and Wamp3. Encountering a Bad Request error when trying to perform an Ajax post. While common wisdom points to CSRF as the root cause, I want to clarify that I have specifically disabled csrf for this particular ...

Enhance your VueJs application with Chart.js without having to rely on refs for seamless reactive

Currently, I am delving into the world of VueJs and experimenting with Chart.js (https://github.com/apertureless/vue-chartjs). I attempted to make a doughnut chart reactive, but I achieved this using the ref property which I suspect may not be the best pr ...

The error message states: "JPA, Maven, and MySQL. Configuration issue detected. Unable to locate class [com.mysql.jdbc

RESOLVED: resolved the issue by placing mysql-connector-java-5.1.x.jar in JAVA_HOME\jre\lib\ext. Hello everyone, I am currently working on developing a demo application using Maven, MySQL, and JPA. Below is my code: pom.xml : <project x ...

The functionality of the onclick event for images in motion is not functioning properly

I am attempting to track the number of clicks on the fox image, but for some reason it's not working as expected. I have confirmed that the onclick function is functioning properly. $(document).ready(function () { var clickCount = 0; $(".fox" ...

Passing values from custom swing components back to the parent class

I have a primary class called myapp in my application, which includes a jLayeredPane. Within this, there is a class named mycustompanel that extends JPanel. Within the myapp class, I've implemented a method to add multiple instances of mycustompanel ...