为什么我的数组缓冲区在服务器端是空的?

时间:2018-10-11 10:15:18

标签: javascript java post jersey

我在JavaScript中有一个方法可以从二进制文件读取到ArrayBuffer并将其发送到Jersey POST方法:

function readAndSendBytes() {
    var file = document.getElementById("entityFileField").files[0],
        reader = new FileReader();
    var entityBytes = reader.readAsArrayBuffer(file);

    reader.onloadend = function () {
        alert(reader.result);
    }

    var xhr = new XMLHttpRequest();
    var url = "/api/upload/e2j";
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/octet-stream");
    xhr.responseType = "json";

    xhr.onload = function (e) {
        var response = xhr.response;
        alert(response);
    }

    xhr.send(reader.result);
}

泽西岛:

@Path("/upload")
public class ParserHandler {
    @POST
    @Path("/e2j")
    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    @Produces(MediaType.APPLICATION_JSON)
    public String entityToJsonTwoElectricBoogaloo(byte[] entityPayload) {
        System.out.println(entityPayload.length);
}

每当我在控制台上打印长度时,该长度始终为0,应为439。我在做什么错了?

2 个答案:

答案 0 :(得分:0)

找到了解决方案!只是将文件和FileReader的发送和初始化以外的所有内容都移到了xhr.onload函数中!

编辑:忘记发布我的解决方案。

function postEntity() {
    var output = document.getElementById("response");
    var file = document.getElementById("entityFileField").files[0];
    var jsonResponse;

    var r = new FileReader();
    r.onloadend = function(e) {
        var data = r.result;

        var xhr = new XMLHttpRequest();
        var url = "/api/upload/entitytojson";
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-type", "application/octet-stream");
        xhr.responseType = "json";

        xhr.onload = function (e) {
            if (xhr.response != null) {
                jsonResponse = JSON.stringify(xhr.response);
                output.innerHTML = jsonResponse;
            }
            else {
                alert("Invalid Entity File");
            }
        }

        xhr.send(data);
    }

    r.readAsBinaryString(file);
}

答案 1 :(得分:0)

不需要使用filereader,您只需发送带有xhr的blob

function sendFile() {
  var file = document.getElementById("entityFileField").files[0];
  var xhr = new XMLHttpRequest();
  var url = "/api/upload/e2j";
  xhr.open("POST", url);
  xhr.setRequestHeader("Content-type", "application/octet-stream");
  xhr.responseType = "json";

  xhr.onload = function (e) {
    var response = xhr.response;
    alert(response);
  }

  xhr.send(file);
}