javascript – Own Image Hosting Page: How to always open an html file but with image given in the url?-ThrowExceptions

Exception or error:

I’m currently working on my own image hosting site: https://img.baeni.de

Everything is working properly but I want to change something.

Currently, when opening a link from a shared image, it just simply opens the image. I want to open another html site with an image instead. The image should be the image which is given in the url.

Example:
Visiting img.baeni.de/u/123.png opens the construct.html file & sets so that the image, which is given in the url, will be shown on that page.

Important: The URL should still be img.baeni.de/u/123.png & NOT img.baeni.de/construct.html

I DON’T want to get spoonfeeded but want to receive some ideas of how you guys would handle something like that.

Best regards,
baeni

How to solve:

I am not sure, but this may work for you.

Put the following in a .htaccess in the u/ folder (or maybe the root folder).

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^u/(.*)$ construct.html?img=$1 [QSA]

When the visitor arrives at img.baeni.de/u/123.png the web server will actually serve the page img.baeni.de/construct.html?img=123.png.

You can use javascript like this to get the URL:

// Will get /u/123.png
  var urlstr = window.location.pathname;

// Will turn it into 123.png
  var imgstr = str.split("/").pop();

To load the image src after the page load, create a container (like a div) to hold the image. Then window.onload can populate this container with the image, or the error image.

<div id="image"></div>

<script>
  // On page load call an immediately invoked function to load the image
  window.onload(

    function(){

      // Will get /u/123.png
      var urlstr = window.location.pathname;

      // Will turn it into 123.png
      var imgstr = "/gfx/" + str.split("/").pop();

      // Error Image
      var errorImg = '/gfx/error.png';

      // Create the image in the div container
      document.getElementById('image').innerHTML="<img src='" + imgstr + "' onerror='this.onerror=null;this.src=\"" + errorImg + "\"'>";

    }()
  );
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *