任何人都可以幫助我嗎?檢索二進制數據
我有一個簡單的測試的Java servlet,如下圖所示:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
byte[] bytes = ReadWaveformAsBinary();
response.setContentType("application/octet-stream");
response.setContentLength(bytes.length);
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.write(bytes, 0, bytes.length);
servletOutputStream.flush();
servletOutputStream.close();
}
此功能。它返回一個包含10個雙精度數字的字節數組。我知道其所有的工作,因爲我可以從如下C#應用程序調用它:
public static bool CallWebServiceDownloadEndPoint(string szWebEndPoint, string szRequest, out double[] data)
{
data = null;
bool bSuccess = true;
WebClient webClient = new WebClient();
try
{
byte[] byteData = webClient.DownloadData(szWebEndPoint + "?" + szRequest);
Array.Reverse(byteData);
data = CreateDoubleArrayFromByteArray(byteData);
Array.Reverse(data);
}
catch
{
bSuccess = false;
}
return bSuccess;
}
所得字節陣列具有80個字節(10×8字節)和10個數字的預期大小均如預期。
我的問題是,我怎麼能通過AJAX調用從JavaScript調用這個Java servlet?
舉例來說,我試過如下:
function AJAXSendString(ajaxRequestObject, szURL, szParams, OnCallCompleted)
{
if (ajaxRequestObject != null)
{
ajaxRequestObject.open("GET", szURL, true);
ajaxRequestObject.responseType = "arraybuffer";
ajaxRequestObject.onreadystatechange = function()
{
if (ajaxRequestObject.readyState == 4)
{
if (ajaxRequestObject.status == 200)
{
var arrayBuffer = ajaxRequestObject.response;
if(arrayBuffer)
{
var byteArray = new Uint8Array(arrayBuffer);
alert(byteArray.byteLength);
}
}
}
}
ajaxRequestObject.send(szParams);
}
但警告框說:19(不是80,我希望的那樣)。
感謝您的任何幫助。
至於建議我嘗試以下方法,但我得到了相同的結果:(
function AJAXSendString2(ajaxRequestObject, szURL, szParams, OnCallCompleted)
{
if (ajaxRequestObject != null)
{
ajaxRequestObject.open("GET", szURL, true);
ajaxRequestObject.responseType = "arraybuffer";
ajaxRequestObject.onload = function(oEvent)
{
var arrayBuffer = ajaxRequestObject.response;
if(arrayBuffer)
{
var byteArray = new Uint8Array(arrayBuffer);
alert(byteArray.byteLength);
}
}
/*ajaxRequestObject.onreadystatechange = function()
{
if (ajaxRequestObject.readyState == 4)
{
if (ajaxRequestObject.status == 200)
{
var arrayBuffer = ajaxRequestObject.response;
if(arrayBuffer)
{
var byteArray = new Uint8Array(arrayBuffer);
alert(byteArray.byteLength);
OnCallCompleted("1,-1,0,0,-1,1");
}
}
}
}*/
ajaxRequestObject.send(szParams);
}
}
我仍然可以看到19,而不是80
'arrayBuffer.byteLength'給你什麼? – Musa
它給了我19,但我期待80 – user3738290