1

In a project I am currently developing, I need to load the content of an image file located in the same directory as the index.html page and the app.js script file (It is a tiny project, so everything is in the same directory). I did that easily with the Fetch API :

var imageBytes
fetch('image.png')
    .then(response => response.blob())
    .then(function(blob) {
        blob.arrayBuffer().then(function (bytes) {
            imageBytes = bytes
        })
    })

It works when my webpage is accessed with a web server. However, I'd like my page to work when it is loaded by clicking the index.html file and using it locally. I understand it is for security reasons, as my browser tries to access a the image with a file:// request, which is blocked. However, my file is part of the website, it is not like if I tried to load a random file in the user filesystem.

I could ask the user to select the image with the <input type="file"> form. But one other thing that could, maybe, work would be to add the image in my HTML page with a standard <img src="image.png" id="myImage"> tag, and load its bytes in JS from there. However, I have no idea of how to do that. I tried getElementById('myImage') but what I get does not seem to contain the image itself, only its attributes. Is there a way to get the content of one of the images in my HTML page in JavaScript ?

Helvinion
  • 87
  • 1
  • 7
  • You can try with `canvas` and `toDataURL()` but likely that this will be forbidden too - https://stackoverflow.com/q/22710627/863110 – Mosh Feu Oct 18 '20 at 07:36

0 Answers0