Search code examples
javascriptsrc

Is there a way to set the src attribute of img or audio/video from binary content


so imagine I perform an ajax request that sends a name of a image file to my PHP server and the server is NOT ALLOWED to send a link to the file ... instead it will send the contents of the file through PHP's readfile(); function. when this data is returned, how should JavaScript set an img element's src attribute e.g

myXMLHttpRequest.onload=function(){
  imgElement.src= /*some way to work with myXMLHttpResponse.reponseText*/;
}

OK, the main point here is to set the src from a string where that string is binary content of an image file.


Solution

  • Yes, this is possible, and regularly done.

    Simply use the URL of your PHP script. Don't bother with XHR.

    <img src="your-image-script.php" />