Home > database >  Download mp3 dynamically by javascript / jquery
Download mp3 dynamically by javascript / jquery

Time:06-22

For example I have a mp3 on the server

http://example.com/test.mp3

Now I want to download this file in javascript.

My current code is like this,then,,, how can I save this file from browser?

  $("#downloadBtn").on("click",function(){
    console.log("startdownload");
      jQuery.ajax({
        url: "http://example.com/test.mp3",
        xhrFields:{
            responseType: 'blob'
        },
        success: function(data){            
          console.log("success");
            var blobData = data;
            var url = window.URL || window.webkitURL;
            var src = url.createObjectURL(data);
        }
    });
  });

CodePudding user response:

Why not just use the download attribute? No JS needed.

<a href="http://example.com/test.mp3" download>Click to download</a>

If you need to fetch a dynamic url, and force a download, you can use this in your success handler, which effectively 'pushes' the resulting url to the user by faking a click on an injected anchor element (using src from your code, as an url):

success: function (data) {
  //from your example
  var blobData = data;
  var url = window.URL || window.webkitURL;
  var src = url.createObjectURL(data);

  if (document.createEvent) {

    //destroy any leftover links from previous attempts
    $('#download_link').remove();

    //create a new link, and set attributes
    let anchor = document.createElement('a');
    anchor.setAttribute('href', src);
    anchor.setAttribute('id', 'download_link');
    anchor.setAttribute('download', data.name);

    //put the anchor in the body, or IE will not trigger a click
    document.body.appendChild(anchor);

    // Create the mouse event
    var ev = document.createEvent("MouseEvents");
    ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

    // Fire the mouse event (fakes a 'click')
    document.getElementById('download_link').dispatchEvent(ev); 

  } else {

    //No createEvent on the document, so this is probably IE < 9
    var hiddenIFrameID = 'hiddenDownloader',
      iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
      iframe = document.createElement('iframe');
      iframe.id = hiddenIFrameID;
      iframe.style.display = 'none';
      document.body.appendChild(iframe);
    }
    iframe.src = src;
  }
}

CodePudding user response:

The code below should do the job:

  $( function() {
     $("#downloadBtn").on("click",function(){
      console.log("startdownload");
        jQuery.ajax({
          url: "http://example.com/test.mp3",
          xhrFields:{
              responseType: 'blob'
          },
          success: function(data){            
            console.log("success");
              var blobData = data;
              var url = window.URL || window.webkitURL;
              var src = url.createObjectURL(data);
              var a = document.createElement('a');
              a.setAttribute('href', src);
              a.setAttribute('download', 'test.mp3');
              var aj = $(a);
              aj.appendTo('body');
              aj[0].click();
              aj.remove();       
          }
      });
    });    
  });

Here is a fiddle with the above code that downloads a .jpeg from imgur.

Update: and a fiddle that downloads an mp3

  • Related