Load image using Ajax with custom headers

What is the correct way to load an image using ajax?

I cannot use normal tag <img/>

as I need to pass some special http headers in the request GET

.
... For this reason, I am somewhat limited to using Ajax. The headers I have to pass to the request are credentials. Without this, it will be impossible to obtain image files.

I was wondering if there is a way to make an ajax request to load data into a tag img

and store the attribute src

as a real image url. I'm not too interested in uploading an image using a database64 url.

+3


source to share


1 answer


The short answer is .... you can't.

The only way you are going to get this image into a tag <img>

and still pass certain http headers is via ajax ... and the response should be a database64 url ​​(or you need to convert it to base64) which can be put in the tag <img>

as the value of the src attribute.



As soon as you change the src attribute of the tag <img>

, the browser will request the image from the server ... and it won't pass any specific headers.

If you want to display an image you either need a tag <img>

(which gives you the constraints I mentioned) or you can put it as a css background for any element, but the same constraints apply. Once you set the url, the browser will load the image without any special headers.

+4


source







All Articles