Handling a Download Result

You can use a download result using a blob. For procedures for implementing blobs, see JavaScript references and technical information on the Internet.

See below for implementation examples.

Showing a downloaded file as an image

You can use the window.URL.createObjectURL() method to show a downloaded file as an image. The following example is a modified version of the success callback for the downloadBody() in the sample code in Downloading an Object Body.

  • success: function(theObject, bodyBlob) {
      var image = new Image();
      image.src = window.URL.createObjectURL(bodyBlob);
      document.body.appendChild(image);
    },
  • then(
      function(params) {
        var bodyBlob = params[1];
        var image = new Image();
        image.src = window.URL.createObjectURL(bodyBlob);
        document.body.appendChild(image);
      }
    )

Alternatively, you can also publish the object body and use the published URL as the image source. This approach works to share the content with other users. However, keep in mind that anyone who knows the published URL can view the image.

Handling a downloaded file as a data stream

You need to convert a blob if you want to reference a downloaded file as a data stream. Here, we will present an example of converting a downloaded file into a BASE64 string.

The following example is a modified version of the success callback for the downloadBody() in the sample code in Downloading an Object Body.

  • success: function(obj, bodyBlob) {
      var reader = new FileReader();
      reader.onload = function() {
        var arrayBuffer = reader.result;
        var base64 = window.btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
      };
      reader.readAsArrayBuffer(bodyBlob);
    },
  • then(
      function(params) {
        var bodyBlob = params[1];
        var reader = new FileReader();
        reader.onload = function() {
          var arrayBuffer = reader.result;
          var base64 = window.btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
        };
        reader.readAsArrayBuffer(bodyBlob);
      }
    )

You cannot directly reference data in a blob. So ,the above code reads a blob as an array buffer and then converts it to a BASE64 string with the btoa() method.