Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Download files with AJAX (axios) / Download files with AJAX (Laravel)
// use responseType: 'blob'
axios({
url: 'http://localhost/download_pdf',
method: 'GET',
responseType: 'blob', // <--
}).then(response => {
const blob_file = response.data;
const file_url = URL.createObjectURL(blob_file);
window.open(file_url); // open file in new tab
});
// or use responseType: 'arraybuffer'
axios({
url: 'http://localhost/download_pdf',
method: 'GET',
responseType: 'arraybuffer', // <--
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'custom_filename.pdf'); // set custom file name
document.body.appendChild(link);
link.click(); // force download file without open new tab
});
// backend on the Laravel (for example)
// file web.php
Route::get('/download_pdf', function () {
$filename = 'labels.pdf';
$pathToFile = public_path().'/'.$filename;
return Response::make(file_get_contents($pathToFile), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'"'
]);
});
// несколько ссылок с простыми pdf для тренировок
// http://www.orimi.com/pdf-test.pdf
// http://www.pdf995.com/samples/pdf.pdf
// https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf
// http://www.africau.edu/images/default/sample.pdf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.