I have an API-Server who responds to requests like this:
http://localhost:8080/slim3/public/api/v1/files/Test1.jpg
http://localhost:8080/slim3/public/api/v1/files/Test2.txt
...
If I put such URL into my browser I can get the download prompt. Now I'm struggeling to process the download of a file via jQuery / Ajax.
Every thread I found here on Stackoverflow tells me to send back the actual download url and open it via window.location
. I don't understand how this is possible
when my server already has the file downloaded for me and I just need to "grab" it somehow on the client-side?
It is clear to me that I can't force the download dialog via jQuery / Javascript. I read this in multiple threads here. But the same threads don't tell me how I can get the direct download url. Or do I mix things up here unfortunately?
Here is what I have:
Client (jQuery)
$(document).ready(function(){
$(document).on('click', '#file', function(e){
e.preventDefault();
var filename = $(this).data('url');
$.ajax({
type : "GET",
cache: false,
url : "http://localhost:8080/slim3/public/api/v1/files/" + filename,
success : function(data) {
console.log(data) // the console writes nothing
//window.location = "data:application/octet-stream," + encodeURIComponent(data); // not working
//var downloadUrl = data.url; // not working
//window.location = downloadUrl; // // not working
},
error : function(data) {}
});
});
});
Server (PHP)
public function show($request, $response, $args)
{
$file = 'C:\xampp\htdocs\slim3\storage\Test1.jpg';
$res = $response->withHeader('Content-Description', 'File Transfer')
->withHeader('Content-Type', 'application/octet-stream')
->withHeader('Content-Disposition', 'attachment;filename="'.basename($file).'"')
->withHeader('Expires', '0')
->withHeader('Cache-Control', 'must-revalidate')
->withHeader('Pragma', 'public')
->withHeader('Content-Length', filesize($file));
readfile($file);
return $res;
}
Solution:
Rob pointed me in the right direction. I actually don't need to do an GET Ajax
request. So the final jQuery function looks exacty like this and works:
$(document).on('click', '#file', function(e){
e.preventDefault();
var filename = $(this).data('url');
window.location = "http://localhost:80/slimmi/public/api/v1/files/" + filename;
});