简体   繁体   中英

Download file from http url by JQuery Ajax

I have on html page input type text. I want paste URL, on example http://www.quicksprout.com/images/foggygoldengatebridge.jpg in this text field and click button "download" and download this file to my computer. I want want to realize this with AJAX. Maybe do you know some AJAX plugins or code that could realize downloading file from HTTP URL?

First MEthod

function SaveToDisk(fileURL, fileName) {
                //alert("yes i m working");
                // for non-IE
                if (!window.ActiveXObject) {
                    var save = document.createElement('a');
                    save.href = fileURL;
                    save.target = '_blank';
                    save.download = fileName || 'unknown';

                    var evt = new MouseEvent('click', {
                        'view': window,
                        'bubbles': true,
                        'cancelable': false
                    });
                    save.dispatchEvent(evt);

                    (window.URL || window.webkitURL).revokeObjectURL(save.href);
                }

                // for IE < 11
                else if ( !! window.ActiveXObject && document.execCommand)     {
                    var _window = window.open(fileURL, '_blank');
                    _window.document.close();
                    _window.document.execCommand('SaveAs', true, fileName || fileURL)
                    _window.close();
                }
           } 

Second MEthod

function downloadme(x,y){

        myTempWindow = window.open(x,'','left=10000,screenX=10000');
        myTempWindow.document.execCommand('SaveAs','null',y);
        myTempWindow.close();
    }

You don't need AJAX to do that, nor would you be able to because of CORS limitations. Instead try something like this.

HTML:

<input type="text" placeholder="URL" id="url"/>
<input type="text" placeholder="Filename" id="name"/>
<a id="download">Download Link</a>

JavaScript:

var url = document.getElementById('url'),
    name = document.getElementById('name'),
    a = document.getElementById('download');

a.addEventListener('click', function () {
    this.setAttribute('src', url.value);
    this.setAttribute('download', name.value);
});

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