Answer the question
In order to leave comments, you need to log in
How to implement file download via AJAX?
Hello
There is a web page with a form. When the button is clicked, data is sent to the server using jQuery.
The request code looks like this:
$.ajax({
url : '/download-action',
type : 'POST',
async : false,
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-TOKEN', $("#token").attr('value'));
},
data : JSON.stringify(sources),
success : function(data) {
}
});
header("Pragma: public");
header("Content-Type: text/plain; charset=utf-8");
header("Content-Disposition: attachment; charset=utf-8; filename=\"file.txt\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($file_content));
echo $file_content;
Answer the question
In order to leave comments, you need to log in
Can't download file via AJAX. Dealt with this recently.
1. On the server, upon receiving an AJAX request, you can prepare a file and form a unique link to it, which you can send in response to the received AJAX request.
2. In the browser, having received a link to the file, open a new window
How to download a file after receiving it via ajax
Convenient when the file takes a long time to create and you need to show the preloader
Example when submitting a web form
$(function () {
$('form').submit(function () {
$('#loader').show();
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'binary',
xhrFields: {
'responseType': 'blob'
},
success: function(data, status, xhr) {
$('#loader').hide();
// if(data.type.indexOf('text/html') != -1){//Если вместо файла получили страницу с ошибкой
// var reader = new FileReader();
// reader.readAsText(data);
// reader.onload = function() {alert(reader.result);};
// return;
// }
var link = document.createElement('a'),
filename = 'file.xlsx';
// if(xhr.getResponseHeader('Content-Disposition')){//имя файла
// filename = xhr.getResponseHeader('Content-Disposition');
// filename=filename.match(/filename="(.*?)"/)[1];
// filename=decodeURIComponent(escape(filename));
// }
link.href = URL.createObjectURL(data);
link.download = filename;
link.click();
}
});
return false;
});
});
Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question