Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to trigger file download?

In public/templates/calendar.html I have

<a href="" id="secret_download_button" style="display:none" download="">

In the same file I have a button (download qr), i make an ajax call from javascript, the qr gets created in /public/uploads/thumbs/qrcodes/'filename' the ajax calls is finished and the following function is called which is in

public/javascript/some.js

function (data) {
        $('#secret_download_button').attr('href',data.content);
        $('#secret_download_button').attr('download','somename');
        $('#secret_download_button').click();
    });

data.content = public/upload/thumbs/qrcodes/someqr.png (example)

I need to use relative paths, not absolute paths. What am I doing wrong ? I am guessing that I am setting the href path wrong. Also from what I read online this solution is not supported by IE. Is there another, simpler, more elegant way of doing this ( I need to be able to specify the name of the file which will be downloaded )

Edit

Solved it server-side in the end. thanks. For anyone else having the same problem I used this:

            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($activity_name . '.png').'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($root . $path . $file_name));
            readfile($root . $path . $file_name);
            exit;
like image 357
myheadhurts Avatar asked Aug 25 '15 15:08

myheadhurts


1 Answers

You're right, the download attribute is not supported by IE nor Edge (supported in Edge 13+) : http://caniuse.com/#feat=download

To have a cross-browser solution, you will have to open the url in the current window :

function (data) {
    window.location.href = data.content;
});

or a new window :

function (data) {
    window.open(data.content);
});

Two limitations:

  • you can't set the filename client-side, you have to set it server side
  • the browser will not download the file if it can read it (like images, pdf...), you will have to use the "save as"
like image 141
Finrod Avatar answered Oct 14 '22 23:10

Finrod