I am trying to download images using jQuery/AJAX in Laravel 8. I get the image in the response, but it is not downloading. Please help me to download the image.
Controller
public function senddata(Request $req)
{
$stamp = new Stamp();
$stamp->company_name = $req->company_name;
$stamp->reg_no = $req->reg_no;
$stamp->color = $req->color;
$stamp->fullname = $req->fullname;
$stamp->email = $req->email;
$stamp->save();
// return Storage::download(public_path('images/Screenshot_1.png'));
$filepath = public_path('images/')."Screenshot_1.png";
return Response::download($filepath);
}
jQuery/AJAX Code
$('#acceptform').submit(function () {
if ($('#acceptform').valid()) {
var company_name = $('#company_name').val();
var reg_no = $('#reg_number').val();
var color = $('input[name="stamp_color"]:checked').val();
var fullname = $('#fullname').val();
var email = $('#email').val();
$.ajax({
type: 'POST',
url: "{{ route('senddata') }}",
data: {company_name: company_name, reg_no: reg_no,
color: color, fullname: fullname, email: email},
xhrFields: {
responseType: 'blob'
},
success: function (res) {
const data = res;
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', 'Screenshot_1.png');
link.click();
}
});
}
});
2
Answers
Why would you use Ajax to download a file, why no simple get request with file id?
If someone needs an answer (even if you do not need ajax to download a file), if you succeeded to get the requested file as a response you can simply download your blob with JavaScript.
Example: