0

Using javascript, I am setting the src property of an image object

    mainImage.src = filePath;

When filePath is something like C:\images\pink.jpg, I have no problems But I found a bug where the filename is of the type:

    C:\images\uploads%2Fcard%2Fimage%2F1574322%2F0b0640a8-cfca-45fa-b1c7-2cfc9a97c146.jpg%2Ffull-fit-in__950x534.jpg

It seems that the %2F is read as a \ character and I end up with a net::ERR_FAILED error. But the filename is literally uploads%2Fcard%2Fimage%2F1574322%2F0b0640a8-cfca-45fa-b1c7-2cfc9a97c146.jpg%2Ffull-fit-in__950x534.jpg.

Is there a way to set the src property of an image with filenames such as these without any error? I am setting this value in an electron project which means that chrome is being used to test. Many Thanks

daibatzu
  • 507
  • 4
  • 16
  • 1
    Are the image given this name structure in your code? It seems like the best option is to clean up the process that is creating these in the first place. – imvain2 Jan 19 '21 at 19:53
  • Did you tried to prepend `file:` to the filepath? Like this: `file://C:\images\uploads%2Fcard%2Fimage%2F1574322%2F0b0640a8-cfca-45fa-b1c7-2cfc9a97c146.jpg%2Ffull-fit-in__950x534.jpg` – mws_souza Jan 19 '21 at 19:56
  • Yes I did. Here is the full error: /C:/Projects/Javascript/photos/test/uploads%2Fcard%2Fimage%2F1574322%2F0b0640a8-cfca-45fa-b1c7-2cfc9a97c146.jpg%2Ffull-fit-in__950x534.jpg:1 GET file:///C:/Projects/Javascript/photos/test/uploads%2Fcard%2Fimage%2F1574322%2F0b0640a8-cfca-45fa-b1c7-2cfc9a97c146.jpg%2Ffull-fit-in__950x534.jpg net::ERR_FAILED – daibatzu Jan 19 '21 at 20:45

1 Answers1

0

encodeURI will do the trick.

let url = 'file:///c:/images/uploads%2Fcard%2Fimage%2F1574322%2F0b0640a8-cfca-45fa-b1c7-2cfc9a97c146.jpg%2Ffull-fit-in__950x534.jpg'

mainImage.src = encodeURI(url);
Elna Haim
  • 545
  • 1
  • 5
  • 19
  • Thanks. The string resolves nicely but I get an error, maybe from electron which says: [5464:0120/021413.476:ERROR:CONSOLE(0)] "Not allowed to load local resource: file:///C:/Users/igweo/OneDrive/Pictures/seamm_jasani.jpg", source: devtools://devtools/bundled/devtools_app.html?remoteBase=https://chrome-devtools-frontend.appspot.com/serve_file/@8eedfc19d05fc36b29e85714af178c99600e271e/&can_dock=true&toolbarColor=rgba(223,223,223,1)&textColor=rgba(0,0,0,1)&experiments=true (0) – daibatzu Jan 20 '21 at 01:17
  • It is coming from Electron, but this is another question, for your question i answered the correct answer, please create a new question with the new issue. you can check this answer it might help: https://stackoverflow.com/questions/41130993/electron-not-allowed-to-load-local-resource please check my answer as the answer if you found it correct. – Elna Haim Jan 20 '21 at 12:09