jQuery AJAX를 사용하여 이진 파일 다운로드
jQuery AJAX를 사용하여 바이너리 오디오 파일을 다운로드하려고 합니다.
보통 다음과 같은 명령어를 발행합니다.
windows.location.href = 'http://marksdomain(dot)com/audioFile.wav' ;
그러나 최근 서버가 응답을 너무 오래 기다려서 게이트웨이 타임아웃 메시지가 나타납니다.
대신 jQuery AJAX를 사용할 것을 제안받았습니다.그렇게 되면 타임아웃을 더 제어할 수 있게 됩니다.
지금까지 플레이한 코드는 다음과 같습니다.
$.ajax({
url: 'http://marksdomain(dot)com/audioFile.wav',
timeout: 999999,
dataType: 'binary',
processData: false, // this one does not seem to do anything ?
success: function (result) {
console.log(result.length);
},
error: function (result, errStatus, errorMessage) {
console.log(errStatus + ' -- ' + errorMessage);
}
};
data Type을 생략하면 바이너리 파일이 서버상의 실제 파일보다 약 3배 커집니다.그러나 dataType을 "binary"로 하면 AJAX에서 다음 오류가 발생합니다.
"No conversion from text to binary"
이전 게시물에서는 jQuery AJAX가 이 방법으로 바이너리 파일을 처리할 수 없는 것처럼 들립니다.
Delivery.js는 실제로 제가 시도하고 있는 것에 대해 상당히 잘 작동하는 것을 발견했지만, 가능하다면 노드 솔루션을 사용하지 않는 것이 좋습니다.
좋은 의견이라도 있나?
XHR을 직접 사용하면 됩니다.다음 예는 MDN에서 가져온 것입니다.
var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
var arrayBuffer = oReq.response;
// if you want to access the bytes:
var byteArray = new Uint8Array(arrayBuffer);
// ...
// If you want to use the image in your DOM:
var blob = new Blob([arrayBuffer], {type: "image/png"});
var url = URL.createObjectURL(blob);
someImageElement.src = url;
// whatever...
};
oReq.send();
$.120 트랜스포트를 설정하고, 여기서 설명한 대로 설정을 변경할 수 있습니다.http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
// use this transport for "binary" data type
$.ajaxTransport("+binary", function (options, originalOptions, jqXHR) {
// check for conditions and support for blob / arraybuffer response type
if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
return {
// create new XMLHttpRequest
send: function (headers, callback) {
// setup all variables
var xhr = new XMLHttpRequest(),
url = options.url,
type = options.type,
async = options.async || true,
// blob or arraybuffer. Default is blob
dataType = options.responseType || "blob",
data = options.data || null,
username = options.username || null,
password = options.password || null;
xhr.addEventListener('load', function () {
var data = {};
data[options.dataType] = xhr.response;
// make callback and send data
callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
});
xhr.open(type, url, async, username, password);
// setup custom headers
for (var i in headers) {
xhr.setRequestHeader(i, headers[i]);
}
xhr.responseType = dataType;
xhr.send(data);
},
abort: function () {
jqXHR.abort();
}
};
}
});
그런 다음 에이잭스 전화를 걸겠습니다.
return $.ajax({
url: url,
method: 'GET',
dataType: 'binary',
processData: 'false',
responseType: 'arraybuffer',
headers: { 'X-Requested-With': 'XMLHttpRequest' }
}).then(function (response) {
var data = new Uint8Array(response);
//do something with the data
return data;
}, function (error) {
alertify.error('There was an error! Error:' + error.name + ':' + error.status)
});
jQuery를 사용해야 하는 경우 다음을 사용할 수 있습니다.$.ajaxSetup()
[ Low Level ]설정을 변경합니다.
예:
// Set up AJAX settings for binary files:
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
if (settings.dataType === 'binary') {
settings.xhr().responseType = 'arraybuffer';
}
}
})
// Make the actual call:
let result = await $.ajax({
url: '/api/export/data',
type: 'GET',
contentType: 'application/json',
dataType: 'binary',
processData: false,
headers: {
token: localStorage.token,
},
});
@user6269864의 답변을 바탕으로 작성됩니다.이것은 틀립니다.dataType
로.binary
다음 항목을 추가하면 결과가 반환됩니다.arraybuffer
.그processData: false
또한 필요하지 않습니다(이 변수에는 반환 데이터가 아닌 서버로 전송된 데이터가 포함됩니다).
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
if (settings.dataType === 'binary')
settings.xhr = () => $.extend(new window.XMLHttpRequest(), {responseType:'arraybuffer'})
}
})
언급URL : https://stackoverflow.com/questions/33902299/using-jquery-ajax-to-download-a-binary-file
'it-source' 카테고리의 다른 글
Django Rest-Framework 중첩된 시리얼라이저 순서 (0) | 2023.02.25 |
---|---|
WordPress에 게시물이 10개 이상 표시되지 않음 (0) | 2023.02.25 |
Gradle과 동등한 Maven 프로파일 (0) | 2023.02.25 |
드라이버 클래스 com.mysql.jdbc를 로드하지 못했습니다.드라이버 (0) | 2023.02.25 |
iOS의 NSDictionary에서 JSON 문자열 생성 (0) | 2023.02.25 |