代码之家  ›  专栏  ›  技术社区  ›  David Faizulaev

Javascript-转发文件供用户下载

  •  1
  • David Faizulaev  · 技术社区  · 5 年前

    我想要一个简单的文件下载,这将做同样的事情:

    <a href="file.doc">Download!</a>
    

    <input type="button" value="Download!">
    <button>Download!</button>
    

    同样,是否可以通过JavaScript触发简单的下载?

    $("#fileRequest").click(function(){ /* code to download? */ });
    

    我肯定 正在寻找一种方法来创建一个看起来像按钮的锚,使用任何后端脚本,或者处理服务器头或mime类型。

    0 回复  |  直到 8 年前
        1
  •  563
  •   MultiplyByZer0 Joke_Sense10    6 年前

    您可以使用HTML5触发下载 download 属性

    <a href="path_to_file" download="proposed_file_name">Download</a>
    

    • path_to_file 是解析为URL的路径 same origin blob: data: file: (这是行不通的)。
    • proposed_file_name 要保存到的文件名。如果为空,浏览器默认为文件名。

    MDN , HTML Standard on downloading HTML Standard on download CanIUse

        2
  •  327
  •   Gray droiddeveloper    8 年前

    <form method="get" action="file.doc">
       <button type="submit">Download!</button>
    </form>
    
        3
  •  107
  •   Ani Menon    9 年前

    HTML:

    <button type="submit" onclick="window.open('file.doc')">Download!</button>
    
        4
  •  79
  •   syntagma    4 年前

    一个简单的JS解决方案:

    function download(url) {
      const a = document.createElement('a')
      a.href = url
      a.download = url.split('/').pop()
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
    
        5
  •  74
  •   Mark Amery Harley Holcombe    5 年前

    使用jQuery:

    $("#fileRequest").click(function() {
        // hope the server sets Content-Disposition: attachment!
        window.location = 'file.doc';
    });
    
        6
  •  26
  •   Cjxcz Odjcayrwl    12 年前

    它也非常愚蠢,没有像使用时那样闪烁的新窗口/选项卡 window.open

    HTML:

    <iframe id="invisible" style="display:none;"></iframe>
    

    function download() {
        var iframe = document.getElementById('invisible');
        iframe.src = "file.doc";
    }
    
        7
  •  18
  •   georgeawg    7 年前

    <a class="btn btn-danger" role="button" href="path_to_file"
       download="proposed_file_name">
      Download
    </a>
    

    记录 in Bootstrap 4 docs ,并在引导程序3中工作。

        8
  •  13
  •   Delconis    9 年前

    我想这就是你一直在寻找的解决方案

    <button type="submit" onclick="window.location.href='file.doc'">Download!</button>
    

    我的Javascript生成了一个CSV文件。因为没有远程URL下载它,所以我使用以下实现。

    downloadCSV: function(data){
        var MIME_TYPE = "text/csv";
    
        var blob = new Blob([data], {type: MIME_TYPE});
        window.location.href = window.URL.createObjectURL(blob);
    }
    
        9
  •  10
  •   starwarswii Georgi Peev    8 年前

    您可以隐藏下载链接并让按钮单击它。

    <button onclick="document.getElementById('link').click()">Download!</button>
    <a id="link" href="file.doc" download hidden></a>
    
        10
  •  8
  •   John Weisz    8 年前

    <input type="button" value="Download Now!" onclick="window.location = 'file.doc';">
    
        11
  •  4
  •   thunderJam    4 年前

    您好,我只包括“下载”一词,效果很好。

    <a href="file.pdf" download>Download</a>
    

    function onStartedDownload(id) {
      console.log(`Started downloading: ${id}`);
    }
    
    function onFailed(error) {
      console.log(`Download failed: ${error}`);
    }
    
    var downloadUrl = "https://example.org/image.png";
    
    var downloading = browser.downloads.download({
      url : downloadUrl,
      filename : 'my-image-again.png',
      conflictAction : 'uniquify'
    });
    
    downloading.then(onStartedDownload, onFailed);
    
        12
  •  3
  •   David Willhite    8 年前

    const download = document.getElementById("fileRequest");
    
    download.addEventListener('click', request);
    
    function request() {
        window.location = 'document.docx';
    }
    .dwnld-cta {
        border-radius: 15px 15px;
        width: 100px;
        line-height: 22px
    }
    <h1>Download File</h1>
    <button id="fileRequest" class="dwnld-cta">Download</button>
        13
  •  2
  •   Suragch Shmidt    4 年前

    在我的测试中,只要使用相对链接,以下内容适用于所有文件类型和浏览器:

    <a href="/assets/hello.txt" download="my_file.txt"><button>Download 2</button></a>
    
    • /assets/hello.txt 只是我网站上的一个相对路径。将其更改为您自己的相对路径。
    • my_file.txt

    解释

    我制作了两个按钮,用两种不同的方法进行测试:

    enter image description here

    <button onclick="window.location.href='/assets/hello.txt';">Download 1</button>
    
    <a href="/assets/hello.txt" download="my_file.txt"><button>Download 2</button></a>
    

    :

    • 按钮1在新浏览器选项卡中打开文本文件。但是,按钮1 下载无法自行打开的文件类型的文件(例如,.apk文件)。

    我在Firefox、Safari和Chrome上进行了测试。

        14
  •  1
  •   slayernoah    10 年前

    JS更新表单的action属性:

    function setFormAction() {
        document.getElementById("myDownloadButtonForm").action = //some code to get the filename;
    }
    

    <body onLoad="setFormAction();">
    

    带有提交按钮的表单标签:

    <form method="get" id="myDownloadButtonForm" action="">
        Click to open document:  
        <button type="submit">Open Document</button>
    </form>
    

    工作:

    <form method="get" id="myDownloadButtonForm" action="javascript:someFunctionToReturnFileName();">
    
        15
  •  1
  •   John Weisz    8 年前

    在你的 <body> </body> 标签,使用以下代码放入按钮:

    <button>
        <a href="file.doc" download>Click to Download!</a>
    </button>
    

        16
  •  1
  •   Mark Amery Harley Holcombe    5 年前

    如果你不能使用表单,另一种方法是 downloadjs

    <div onClick=(()=>{downloadjs(url, filename)})/>
    

    *它是jsx/react语法,但可以在纯html中使用

        17
  •  1
  •   m24197    4 年前

    <a href="file.doc"><button>Download!</button></a>
    这将下载文件作为 .doc 不支持在浏览器中打开文件扩展名 .
    text-decoration 将有助于改变或删除链接的文本装饰。

        18
  •  0
  •   Sebi Nechita    4 年前

    如果要下载的文件不在同一来源上,但希望能够下载,则可以使用 Content-Disposition header . 确保服务器在响应文件请求时包含标头。

    设置一个值,如 Content-Disposition: attachment

    简单的 <a href="http://www.notMyOrigin.com/file.txt">Download</a> 在这种情况下,指向您的文件应该下载它。

        19
  •  -1
  •   BananaAcid    6 年前

    file.doc?foo=bar&jon=doe 是在表单中添加隐藏字段

    <form method="get" action="file.doc">
      <input type="hidden" name="foo" value="bar" />
      <input type="hidden" name="john" value="doe" />
      <button type="submit">Download Now</button>
    </form>
    

        20
  •  -1
  •   sourabh sharma    5 年前

    我提出的解决方案是,您可以在锚标记中使用download属性,但它仅在您的html文件位于服务器上时才起作用。但您可能会遇到这样的问题:在设计一个简单的html页面时,我们如何检查您是否可以使用VS code live server或bracket live server,您将看到您的下载属性将起作用,但如果您试图通过双击html页面打开它,它将打开文件,而不是下载它。 结论:锚定标记中的属性下载仅在html文件不是服务器时有效。

        21
  •  -7
  •   Brana    8 年前

    对我来说,用点击按钮代替锚文本效果非常好。

    <a href="file.doc"><button>Download!</button></a>
    

    按照大多数规则,这可能不好,但看起来相当不错。

        22
  •  -10
  •   John Weisz    8 年前

    如果你使用 <a> 标记,不要忘记使用指向该文件的整个url,即:

    <a href="http://www.example.com/folder1/file.doc">Download</a>