Force download a pdf link using javascript/ajax/jquery

前端 未结 7 2040
夕颜
夕颜 2020-11-27 04:51

suppose we have a pdf link \"http://manuals.info.apple.com/en/iphone_user_guide.pdf\"(just for example and to let u know that file is not on my server, i only have the link)

7条回答
  •  佛祖请我去吃肉
    2020-11-27 05:32

    Here is a Javascript solution (for folks like me who were looking for an answer to the title):

    function SaveToDisk(fileURL, fileName) {
        // 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();
        }
    }
    

    source: http://muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html

    Unfortunately the working for me with IE11, which is not accepting new MouseEvent. I use the following in that case:

    //...
    try {
        var evt = new MouseEvent(...);
    } catch (e) {
        window.open(fileURL, fileName);
    }
    //...
    

提交回复
热议问题