Last active
April 19, 2023 16:27
-
-
Save alexey-kar/8d616bdf3986117a69c8fbc8bdf3fb9b to your computer and use it in GitHub Desktop.
Download files with AJAX (axios) / Download files with AJAX (Laravel)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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