skip to Main Content

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


  1. Why would you use Ajax to download a file, why no simple get request with file id?

    Login or Signup to reply.
  2. 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:

    function downloadTC(path) {
        let fd = new FormData;
        fd.append('fileName', path);    
        $.ajax({
            async: true,
            url: '{{ route("download") }}',
            type:"POST",
            data: fd,
            cache: false,
            processData: false,
            contentType: false,
            // defining the response as a binary file
            xhrFields: { responseType: 'blob' },  
            success: function(response) {
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                var url = window.URL.createObjectURL(response);
                a.href = url;
                a.download = path;
                a.click();
                window.URL.revokeObjectURL(url);
            },
            error: function(blob) {
                console.log(blob);
            }
        }); 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search