shahith
shahith

Reputation: 1

image preview in javascript

The following code doesn't work in Firefox and Chrome but works in IE. Can anyone tell me why it doesn't work in browser except IE with solution. Thanks in advance.

<html>
<head>
<script>
function hello()
{
    var a=document.getElementById("upload").value;
    alert(a);
    document.getElementById("previewIMG").src=a;
    document.getElementById("previewIMG").style.display="block";
}

</script>

</head>
<body>
<form name="img"  enctype="multipart/form-data">
<input type="file" name="upload" id="upload" />
<input type="button" name="submit" value="Upload Me Now" onClick="javascript:hello();">
<img id="previewIMG" src="" style="display:none;" />
</form>
</body>
</html>

Upvotes: 0

Views: 3349

Answers (2)

Ram
Ram

Reputation: 21

You can not preview images before actually uploading the image to server.

  1. Let user select the image to be uploaded (.jpg file, for example)

  2. Upload the file to server using AJAX

  3. Display a thumbnail using AJAX

In step 2 above, you may want to upload it to a temporary directory on server so that you can remove it in periodic cleanup.

Upvotes: 2

Pekka
Pekka

Reputation: 449395

There are two problems with this:

  1. Modern browsers don't expose the full path to files selected in file uploads any more. They show something like this:

    C:\Fakepath\Filename.txt

    unfortunately, that destroys the possibility of having a local image preview.

  2. Modern browsers don't allow embedding local image resources, also for security reasons, so even if 1.) didn't exist, it wouldn't work because of this.

You'd have to use an alternative method to get that, e.g. a Flash based uploader like SWFUpload. This also becomes possible again with the HTML 5 file API. I imagine you'd have to fetch the image data, and draw it into a canvas that is your preview image.

Edit: This jQuery library seems like the perfect way to go. It provides an API driven upload facility with image preview functionality that should work in all modern browsers (except IE). Thanks @Shadow Wizard!

Upvotes: 4

Related Questions