简体   繁体   中英

Downloading text file when CTRL is pressed

Im trying to download text files, when CTRL (17) is pressed , its working fine but now my code working when CTRL is pressed, then add atributes to 'download' button, and then starting the download.

There is any solution to do: when CTRL is pressed then start the download without need to press 'download' button?

  else if (e.originalEvent.keyCode === 17)
        {
            var file_name = e.target.innerText;

            var path = "files/" + file_name;

            var rawFile = new XMLHttpRequest();

            rawFile.open("GET", path, false);

            rawFile.onreadystatechange = function ()
            {
                var allText = rawFile.responseText;

                var fileName = file_name;
                var myFile = new Blob([allText], {type: 'text/plain'});

                window.URL = window.URL || window.webkitURL;
                document.getElementById('download').setAttribute('href', window.URL.createObjectURL(myFile));
                document.getElementById('download').setAttribute('download', fileName);
            };
            rawFile.send(null);
        }
        var file_name = e.target.innerText;

        var path = "files/" + file_name;

        var rawFile = new XMLHttpRequest();

        rawFile.open("GET", path, false);

        rawFile.onreadystatechange = function ()
        {
            var allText = rawFile.responseText;

            var fileName = file_name;
            var myFile = new Blob([allText], {type: 'text/plain'});

            window.URL = window.URL || window.webkitURL;
            document.getElementById('download').setAttribute('href', window.URL.createObjectURL(myFile));
            document.getElementById('download').setAttribute('download', fileName);

            $("#download").click();//click here

        };
        rawFile.send(null);

You can click that item programmatically. You can do it after set attributes.

If anyone care, here is the answer:

document.getElementById("download").click();

Thank you btw :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM