最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Download audio file on html anchor link click independant of browser action - Stack Overflow

programmeradmin2浏览0评论

I am having an anchor link on the page which points to an MP3 file. I want to be able to download this file with Right-click + Save Target As.. and also by single clicking on the link.

Currently, I am facing a problem where different browsers have different behavior. IE plays the file in WMP, Firefox prompts the download box and Chrome starts playing file inline. Expected behavior on single click is that browser should either download the file or give me a download dialog.

I have tried following:

  • Creating a hidden iframe on the page and giving it is as target for my anchor link, also tried creating a form with my desired MP3 file location as its action inside this iframe and submitting the form on anchor link click event
  • Setting window.location = MP3 URL on link click
  • Tried multiple binations of window.open

None of these has been able to help me. I just can't get the download dialog on link-click.

The innocent anchor link looks like:

<a id="someID" href="myMP3file" target="whatever" title="Download" class="someClass">Download Me!</a>

I am having an anchor link on the page which points to an MP3 file. I want to be able to download this file with Right-click + Save Target As.. and also by single clicking on the link.

Currently, I am facing a problem where different browsers have different behavior. IE plays the file in WMP, Firefox prompts the download box and Chrome starts playing file inline. Expected behavior on single click is that browser should either download the file or give me a download dialog.

I have tried following:

  • Creating a hidden iframe on the page and giving it is as target for my anchor link, also tried creating a form with my desired MP3 file location as its action inside this iframe and submitting the form on anchor link click event
  • Setting window.location = MP3 URL on link click
  • Tried multiple binations of window.open

None of these has been able to help me. I just can't get the download dialog on link-click.

The innocent anchor link looks like:

<a id="someID" href="myMP3file" target="whatever" title="Download" class="someClass">Download Me!</a>
Share Improve this question edited Dec 12, 2012 at 23:51 skink 5,7666 gold badges40 silver badges64 bronze badges asked May 9, 2012 at 9:11 weberweber 431 gold badge2 silver badges7 bronze badges 5
  • If I'm not mistaken, what you're asking for is not possible using HTML alone. Do you have some server-side language support on your server? (e.g. PHP) Are you using an Apache server? If so, can you create an .htaccess file? If what I'm asking is Gibberish to you, please let me know :) – iMoses Commented May 9, 2012 at 9:20
  • This question looks like it will help stackoverflow./questions/4210406/simple-html-anchor-question – Crab Bucket Commented May 9, 2012 at 9:23
  • @CrabBucket - Thanks! I will try to check if any of suggested solution on this post can help me. But, I don't think I have access to the server that serves the file! – weber Commented May 9, 2012 at 9:30
  • The you will be in the asp code behind - this might help stackoverflow./questions/5596747/… – Crab Bucket Commented May 9, 2012 at 11:02
  • @CrabBucket - Thanks again! Maybe this can help me, I will work on this!!And if I face troubles, I guess I could bug you again :) – weber Commented May 9, 2012 at 12:36
Add a ment  | 

3 Answers 3

Reset to default 1

Just to post the beginnings of a proper answer. I think I would use a http handler (.ashx) file to code up some custom handling for these files - this tutorial shows an example.

Your link would be something like

<a href="MyMp3Handler.ashx?fileName=MyFile">Click here to download</a>

The handler would do the streaming work.

Example of what the handler might look like (based on this SO question)

public void ProcessRequest (HttpContext context) {

    var filePath = Server.MapPath(context.Request.QueryString["fileName"].ToString()) + ".mp3";          
    if (!File.Exists(filePath))             
        return;          

    var fileInfo = new System.IO.FileInfo(filePath);         
    Response.ContentType = "application/octet-stream";         
    Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));         
    Response.AddHeader("Content-Length", fileInfo.Length.ToString());         
    Response.WriteFile(filePath);         
    Response.End();
}

The handler also needs to be registered in the web.config.

Note though - this is off the top of my head so code will need tweaking to work. Just thought I'd pop in how i would start off

Additional Note

A colleague has just pointed out that even with content type set to application/octet-stream it is still up to the browser implementation of how that gets rendered so it still may not stream. That said I did something similar but in PHP and I got the mp3 file streaming down in Firefox, IE and Chrome so the principle does work. I provided the example in asp since that is what your question was tagged as.

@CrabBucket - Here's how I solved my issue!! Works great for me :) I was using a controller action to initiate this download from this server side (this is why I did not use a handler). Returning an http response from the controller seemed tricky initially but then I figured out a way to cheat the thing ;) I had to write the following code inside my controller action -

{
    HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(FileURL);
    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

    Stream myStream = myResponse.GetResponseStream();

    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition", "attachment; filename=\"SaveMe.MP3\"");

    var readBytes = 10000000;
    var myAudResponse = new byte[readBytes];
    int fileLength;
    do {
        fileLength = myStream.Read(myAudResponse, 0, (int)readBytes);
        Response.OutputStream.Write(myAudResponse, 0, fileLength);
        Response.Flush();
    } while (fileLength > 0);
    myStream.Close();

    return new EmptyResult();
}

Use the basic Try-Catch, etc as per your wisdom :) A lot of thanks to various web-forums and also to CrabBucket (the SO question from where you posted the code, had an answer which was very much help!) goes without saying!


Sorry for multiple edits! My code failed for a moment. I guess, loops are always the way to go!!!

You can simply use the anchor tag's "download" attribute.

<a href='your_link' download='file_name'>Download_ME!</a>

This worked for me and personally, I prefer to stick with whatever default customizations are provided.

发布评论

评论列表(0)

  1. 暂无评论