简体   繁体   中英

Download audio file on html anchor link click independant of browser action

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 combinations 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>

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.net 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM