我在这里指定了一个非常类似的需求。

我需要有用户的浏览器手动启动下载时$('a#someID').click();

但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。

相反,我想在新窗口/标签中打开下载。这怎么可能呢?


当前回答

在尝试下载文件时,会发生很多小事情。浏览器之间的不一致性本身就是一场噩梦。我最终使用了这个很棒的小图书馆。 https://github.com/rndme/download

它的优点是它的灵活性,不仅url,而且客户端数据你想要下载。

文本字符串 文本dataURL 文本的团 文本数组 html字符串 html的团 ajax回调 二进制文件

其他回答

我建议您使用mousedown事件,它被称为BEFORE the click事件。这样,浏览器就可以自然地处理点击事件,从而避免了任何奇怪的代码:

(function ($) {


    // with this solution, the browser handles the download link naturally (tested in chrome and firefox)
    $(document).ready(function () {

        var url = '/private/downloads/myfile123.pdf';
        $("a#someID").on('mousedown', function () {
            $(this).attr("href", url);
        });

    });
})(jQuery);

注意:并非所有浏览器都支持。

我正在寻找一种方法,使用jquery下载文件,而不必从一开始就在href属性中设置文件url。

jQuery (< / >, { id:“downloadFile”, href:“http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png”, 风格:“显示:隐藏。” 下载:“ }) .appendTo(身体的); $ (" # downloadFile ") [0] .click (); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>

这些函数在stacktrace.js中使用:

/**
 * Try XHR methods in order and store XHR factory.
 *
 * @return <Function> XHR function or equivalent
 */
var createXMLHTTPObject = function() {
    var xmlhttp, XMLHttpFactories = [
        function() {
            return new XMLHttpRequest();
        }, function() {
            return new ActiveXObject('Msxml2.XMLHTTP');
        }, function() {
            return new ActiveXObject('Msxml3.XMLHTTP');
        }, function() {
            return new ActiveXObject('Microsoft.XMLHTTP');
        }
    ];
    for (var i = 0; i < XMLHttpFactories.length; i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
            // Use memoization to cache the factory
            createXMLHTTPObject = XMLHttpFactories[i];
            return xmlhttp;
        } catch (e) {
        }
    }
}

/**
 * @return the text from a given URL
 */
function ajax(url) {
    var req = createXMLHTTPObject();
    if (req) {
        try {
            req.open('GET', url, false);
            req.send(null);
            return req.responseText;
        } catch (e) {
        }
    }
    return '';
}

hitesh在2013年12月30日提交的答案实际上是有效的。只是需要一点点调整:

PHP文件可以调用自己。换句话说,只需创建一个名为saveass .php的文件,并将此代码放入其中…

        <a href="saveAs.php?file_source=YourDataFile.pdf">Download pdf here</a>

    <?php
        if (isset($_GET['file_source'])) {
            $fullPath = $_GET['file_source'];
            if($fullPath) {
                $fsize = filesize($fullPath);
                $path_parts = pathinfo($fullPath);
                $ext = strtolower($path_parts["extension"]);
                switch ($ext) {
                    case "pdf":
                    header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
                    header("Content-type: application/pdf"); // add here more headers for diff. extensions
                    break;
                    default;
                    header("Content-type: application/octet-stream");
                    header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
                }
                if($fsize) {//checking if file size exist
                  header("Content-length: $fsize");
                }
                readfile($fullPath);
                exit;
            }
        }
    ?>

也许只是让你的javascript打开一个只下载文件的页面,比如当你把一个下载链接拖到一个新选项卡:

Window.open("https://www.MyServer.
Org/downloads/ardiuno/WgiWho=?:8080")

打开窗口,打开一个自动关闭的下载页面。