Search code examples
javascriptxmlhttprequestblob

javascript createObjectURL corrupt file


im using the following javascript to create an object url, the only problem is when loading the url blob:http:///mysite.com/randomhash the file is corrupt.

var audioFile = null;
var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
              audioFile = new Blob([xhttp.response], {type: 'audio/mp3'});
          }
        };
        xhttp.open("GET", "myMp3File.mp3", false);
        xhttp.send();

var file = new File([audioFile], "myMp3File.mp3", {type: "audio/mp3", lastModified: Date.now()});  

any ideas as to why this would create a blob url with a corrupt mp3 ?


Solution

  • Multiple problems here.
    First, you are dealing with asynchronous code. You will need to use a callback in order to use the response of your XHR request.

    Then, even if you did so, there are good chances that it will still not work. This is because the response you get is plain text UTF16 and that some bytes will get mangled by encoding.

    The real solution in your case is to directly request the response as a Blob.
    You can do so with the XMLHttpRequest.responseType parameter.

    var xhttp = new XMLHttpRequest();
    xhttp.responseType = 'blob';
    xhttp.onload = function(e) {
      var blob = xhttp.response;
      callback(blob);
    };
    xhttp.open...
    

    And now in your callback you will be able to create a blobURI directly from this blob.

    function callback(blob) {
      var url = URL.createObjectURL(blob);
      ...
    

    Also, if all you want is to display this file, there is no point in creating a File from it, the only web API it would make a difference if it was a File and not just a Blob is Formdata.append method, and even there, it's not that useful.