Force external download url

前端 未结 2 1256
天涯浪人
天涯浪人 2020-12-03 21:39

I want to host on my webpage an external url containing a mp3 file. The problem is that clicking on that link will open the player, i have to right click and \"Save link as\

相关标签:
2条回答
  • 2020-12-03 22:09

    EDIT: The answer below applies if you have control over the target MP3 file only, not if it is an external link

    The link should not go directly to the MP3 file, but to a piece of logic (are you using ASPX, for instance? In that case you can use an .aspx page as the target, or you can create an HTTP handler for the .mp3 extension) that adds an HTTP header to the output that contains the line:

    Content-Disposition: attachment;filename="whatever.mp3";
    

    This will instruct the browser to treat the contents of the output as a file to save locally.

    0 讨论(0)
  • 2020-12-03 22:20

    Now the HTML5 spec defines a very useful download attribute on hyperlinks that basically allows to force download behavior on client-side, regardless of what comes in Content-Type and Content-Disposition from the server:

    In some cases, resources are intended for later use rather than immediate viewing. To indicate that a resource is intended to be downloaded for use later, rather than immediately used, the download attribute can be specified on the a or area element that creates the hyperlink to that resource.

    <...>

    The download attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. The attribute may have a value; the value, if any, specifies the default filename that the author recommends for use in labeling the resource in a local file system.

    So all you need to do is add the attribute to your hyperlink and the browsers that support it would understand that the content needs to be downloaded:

    <a href="http://example.com/media.mp3" download>Download Your File</a>
    

    You can even suggest a different name for the downloaded file by setting the attribute value:

    <a href="http://example.com/media.mp3" download="check this out.mp3">Download Your File</a>
    

    More info and demos:

    • Downloading resources in HTML5: a[download] (HTML5 Rocks)
    • HTML5 download Attribute (David Walsh)

    Browser support: caniuse.com


    Downloading generated content

    You can even make a link that will download a content that you generated, as long as there is a way to get a base64-encoded data URI for it:

    <a href="data:application/octet-stream;base64,YOUR_ENCODED_DATA" download="song.mp3">Download</a>
    

    For more details on saving generated content, refer to this article by Eli Grey:

    Saving generated files on the client-side

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