Click to See Complete Forum and Search --> : Converting a Windows path to an SRC value


karayan
05-28-2003, 08:24 PM
I need to input a Windows path/filename and place it as an SRC in an <img> tag. The way I did it goes something like this: (the actual code I'm using is far more complex)

<form name="test">
<input type="file" name="testinp" width="60">
<input type="button" value="CLICK" onClick="trythis()">
</form>

<script>
function trythis() {

document.write("<img src = 'file:///" + document.test.testinp.value + "'>");

}

This writes into the document a line with <img src='file:\\\blabla'> where blabla is the path I just read from the file input in the form. This works well on IE even though the path the file input reads is full of backslashes (in the undying DOS path format). IE automatically converts the backslashes to slashes, etc. Even if folder names have blank spaces, IE replaces the blanks with %20. HOWEVER, if any item in the path has an apostrophe (=single quote mark) the script falls apart. (For example: C:\Joe's files\image.jpg)

Two questions then: 1) How do I handle the single quote marks?

2) Any other characters that might be in the path that I need to worry about?

Also, is there an easier and worry-free way to convert a path to an SRC value?

<grateful>Thanks.</grateful>

George

karayan
05-28-2003, 09:46 PM
That's not really the problem. I tried the proposed fix and it didn't work either. The single quotes are in the original path.

For example, if the path is:

C:\Joe\image.jpg

IE automatically converts it and my src looks right:

file:///C:/Joe/image.jpg

which works fine.

But if the original path happens to have a single quote in it, such as an apostrophe, like:

C:\Joe's files\image.jpg

the string that the file input returns to me is:

C:\Joe\'s%20files\image1.jpg

What happened? There is an extra backslash where the apostrophe was, because the apostrophe needs an escape character to be represented in a Javascript string. Hence: a single quote ' became backslash-quote \'

But now, that extra backslash acts as a folder delimiter in the DOS path, as if the path was:

C: --> Joe --> 's files --> image1.jpg

So, the src ends up being:

file:///C:/Joe/'s%20files/image1.jpg

No such path exists, of course, and the src doesn't open. If I try to remove the extra backslash before wiritng the <img>, the single quote without escape will ruin the string and cause Javascript error.

How do I handle this?

George

karayan
05-28-2003, 10:05 PM
I think I figured it out. For posterity, here is the solution:

After generating the <img> with the funny path, I subject it to a:

.replace(/\/'/g,"'")

to get rid of the extra slash(es). The solution is not perfect (as somebody might have MEANT to start the name of a folder with an apostrophe), but...

Still makes me nervous that I may have forgotten some other "special" character that might cause proglems in paths.

Any help will be appreciated.