Search code examples
javascriptjavaajaxhttp

Pass bytes array from AJAX to Java


I'm trying to send a byte array to the server through AJAX:

$.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");
  }
});

And trying to extract that array from httpExchange, but the content of requestBody is empty:

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

    InputStream requestBody = httpExchange.getRequestBody();

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

enter image description here

Actually BufferedInputStream is contained inside the requestBody, but it is unreachable.

Any ideas how can I correctly pass the byte array through JSON to HttpExchange?


Solution

  • The problem was that I didn't notice that my initial AJAX request sent the "OPTIONS" HTTP method which means that I had to treat it as a preflight request. After adding some headers my server side code now looks like this:

    @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
    }
    

    Now after processing a request with the "OPTIONS" method, AJAX automatically send a proper "POST" request.