views:

108

answers:

6

is there a way to load the full binary of an image in javascript?
what i want to do is to allow the user to preview an image before uploading it.
ie the user selects an image on his local drive (C:\image.jpg) , view it, and decides to upload or cancel.
i tried to set the source to the image path, but it didn't work since it is outside the webapplication project folder.
any help?

A: 

You can do something like this:

<img id="preview" src="" style="display:none;" />

<form>
....
<input type="file" id="file" />
....
</form>

<script type="text/javascript">
  var file = document.getElementById("file");
  var img = document.getElementById("preview");

  file.onchange = function(){
    img.src = file.value;
    img.style.display = 'block';
  };
</script>
Web Logic
This works only in IE, but not Chrome and FireFox
Rafal Ziolkowski
Indeed. IE has an age-old bug that it includes the full client side path instead of only the filename in the file field value. Don't let your code rely on bugs.
BalusC
A: 

There is no easy way, what You could do:

  • Preload image with some ajax file uploader to temp area and then let user decide
  • Use some third party written solution (f.ex. some flash component)

Here there is also similar question: http://stackoverflow.com/questions/922057/is-it-possible-to-preview-local-images-before-uploading-them-via-a-form

Rafal Ziolkowski
A: 

You need server cooperation to access the image binary data. You won't be able to use the "Upload Form" to access the file info without uploading it to a server.

You could however do something like tell the user to paste the source binary data of the image in a textarea or something, then you can use JavaScript to load that binary data and display the actual image.

Luca Matteis
A: 

This is available in some browsers via the HTML5 file access API. Here is the Firefox documentation for file access.

Neall
A: 

As answered several times, you can't do this with plain HTML/JavaScript due to security restrictions. You need to send the image anyway. You can however handle this using a Java Applet since it runs entirely at the client machine and offers more control than HTML/JS. There are several free and ready-to-use ones. JumpLoader looks good and some major sites also uses it. With Flash it should also be possible, but I am not sure which ones offers this functionality. Check/tryout some Flash Multi File Uploaders.

BalusC
I have a hard time in understanding the downvote so that I can correct/improve the answer where applicable. Is it because I mentioned about a Java Applet in a question tagged with ASP? Nevertheless, you're welcome :)
BalusC
A: 

thx for your posts, but i ended up creating a temp folder on the server that stores the uploaded image using ajax. and when the user saves the data, the image is moved to another location, and the temp folder is deleted.

scatman