0

I'm working on a JS React app that stores and does transformations at the XML level on large SVGs(1-5MB) and can display the results in the browser. I'm using AWS Amplify to handle the backend, but all documentation I have found is for displaying images in tags via URI and nothing on loading S3 content into state, for example.

Is it possible to get bulk text directly from S3/Amplify Storage instead of having to go through the URI?
Is there a different AWS offering more applicable for this use-case?

EDIT1: I've found another post that I think can help me solve my problem. I'll post back with results.

Return HTML content as a string, given URL. Javascript Function

Gerard Sans
  • 2,269
  • 1
  • 13
  • 13

2 Answers2

0

You can use this code to transform a URL into an URI.

function getDataUri(url, callback) {
    var image = new Image();

    image.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
        canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size

        canvas.getContext('2d').drawImage(this, 0, 0);

        // Get raw image data
        callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));

        // ... or get as Data URI
        callback(canvas.toDataURL('image/png'));
    };

    image.src = url;
}

// Usage
getDataUri('/logo.png', function(dataUri) {
    // Do whatever you'd like with the Data URI!
            this.setState({
              fileUrl: dataUri
            })
});
Gerard Sans
  • 2,269
  • 1
  • 13
  • 13
  • Thanks for the reply, Gerard. I'm not using canvas as it doesn't support some SVG feature I need currently. – user2585754 Aug 09 '20 at 20:33
  • Have you tried it? This is using canvas to capture the rendering in the Image element using the data Uri. As far as I know the rendering is handled by the Image element not the canvas. – Gerard Sans Aug 10 '20 at 11:53
0

I was asking the wrong question. The Amplify Storage API can't give you the actual data, just a URL where you can get it. I ended up crafting an XMLHttpRequest to get the data from the URL provided by Amplify Storage and doing my transforms on that. Adding Promises to Christian Pietsch's answer here solved my problem.

httpGet = async (theUrl: string) => {
  const promise = new Promise((resolve, reject) => {
    const xmlhttp = new XMLHttpRequest(); //not supporting IE 6 or below
    xmlhttp.onreadystatechange = () => {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        resolve(xmlhttp.responseText);
      }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();
  });
  const data = await promise;
  return data;
}