Download File Using Javascript/jQuery

前端 未结 28 2922
悲&欢浪女
悲&欢浪女 2020-11-21 05:11

I have a very similar requirement specified here.

I need to have the user\'s browser start a download manually when $(\'a#someID\').click();

But

相关标签:
28条回答
  • 2020-11-21 05:35

    Note: Not supported in all browsers.

    I was looking for a way to download a file using jquery without having to set the file url in the href attribute from the beginning.

    jQuery('<a/>', {
        id: 'downloadFile',
        href: 'http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png',
        style: 'display:hidden;',
        download: ''
    }).appendTo('body');
    
    $("#downloadFile")[0].click();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2020-11-21 05:37

    Using anchor tag and PHP it can be done, Check this answer

    JQuery Ajax call for PDF file download

    HTML
        <a href="www.example.com/download_file.php?file_source=example.pdf">Download pdf here</a>
    
    PHP
    <?php
    $fullPath = $_GET['fileSource'];
    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;
    }
    ?>
    

    I am checking for file size because if you load pdf from CDN cloudfront, you won`t get the size of document which forces the document to download in 0kb, To avoid this i am checking with this condition

     if($fsize) {//checking if file size exist
          header("Content-length: $fsize");
        }
    
    0 讨论(0)
  • 2020-11-21 05:38

    If you are already using jQuery, you could take adventage of it to produce a smaller snippet
    A jQuery version of Andrew's answer:

    var $idown;  // Keep it outside of the function, so it's initialized once.
    downloadURL : function(url) {
      if ($idown) {
        $idown.attr('src',url);
      } else {
        $idown = $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
      }
    },
    //... How to use it:
    downloadURL('http://whatever.com/file.pdf');
    
    0 讨论(0)
  • 2020-11-21 05:38

    This could be helpful if you are not require to navigate another page. This is base javascript function, so can be used in any platform where backend is in Javascript

    window.location.assign('any url or file path')
    
    0 讨论(0)
  • 2020-11-21 05:39

    I suggest you use the mousedown event, which is called BEFORE the click event. That way, the browser handles the click event naturally, which avoids any code weirdness:

    (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);
    
    0 讨论(0)
  • 2020-11-21 05:41

    I'm surprised not a lot of people know about the download attribute for a elements. Please help spread the word about it! You can have a hidden html link, and fake a click on it. If the html link has the download attribute it downloads the file, not views it, no matter what. Here's the code. It will download a cat picture if it can find it.

    document.getElementById('download').click();
    <a href="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M" download id="download" hidden></a>

    Note: This is not supported on all browsers: http://www.w3schools.com/tags/att_a_download.asp

    0 讨论(0)
提交回复
热议问题