0

we have used aws s3 for image storing. When we tried convert image to base64. code working fine javascript but code is not angular

javascript code:

function getBase64Image(imgUrl, callback) {
    var img = new Image();
    // onload fires when the image is fully loadded, and has width and height
    img.onload = function(){
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0);
      var dataURL = canvas.toDataURL("image/png"),
          dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

      callback(dataURL); // the base64 string

    };

    // set attributes and src 
    img.setAttribute('crossOrigin', 'anonymous'); //
    img.src = imgUrl;

}
this.getBase64Image("imageURL", function(base64image){
     console.log(base64image);
});

It is working fine in javascript but angular throws below error

Access to image at 'https://examplecros.s3.us-east-2.amazonaws.com/images5.jpg' from origin 'http//localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 5.jpg:1
Failed to load resource: net::ERR_FAILED

2 Answers 2

1

AWS S3 and your local are 2 different domains and you have already consider to set its corresponding property:

img.crossOrigin = 'Anonymous'.

Also, you have to config cross domain setting in your backend by this syntax:

CORS_ORIGIN_ALLOW_ALL = True.

If the problem exist yet, try adding a random parameter to your image URL to avoid your app getting the img from local cache:

img.src = imgUrl + '?r=' + Math.floor(Math.random()*100000);

I used the above steps and solved my problem witch was similar to yours.

reference

Sign up to request clarification or add additional context in comments.

Comments

0

This is a security restriction from the browser because the origins are different. You can do the following workarounds to do this.

add,

img.crossOrigin = '*'

and try using pre-signed URL for the object in s3(as image src) instead of direct url

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.