9

I am trying to design a module in which I would like to show a preview of the image to the user before he uploads the image to database.

I have found a solution which works for Firefox but is not working for IE and Chrome...Can someone help me out.

Here is my code:-

     function imageURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function(e) {
                $('#replaceMe').attr('src', e.target.result)
                 .width(100)
                 .height(100);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

And I am calling this function on change event of the file input control:-

<input type="file" class="file" onchange="imageURL(this)" />

And also I have tried this url steps but it doesnt work for IE7 and 8 and Chrome.

Meenal
  • 2,879
  • 5
  • 19
  • 43
abhijit
  • 1,958
  • 3
  • 28
  • 39
  • try appending file:/// in start of the path – Shakeeb Ahmed May 02 '11 at 06:34
  • hy, if you open an image in browser from local the url is like this file:///C:/path/image.jpg....so you get the path just append file:/// in the start...... – Shakeeb Ahmed May 02 '11 at 22:42
  • the only way i know how to do this - seen it done before- is to make a java applet run on the client. Then it has permissions to local resources - they can view, select, delete, etc - crop, edit, effects.. Then in the applet send a request to where you need to upload if they are happy. I think Facebook or Picasa used this approach a few years ago- but that was also mainly to compress images on the client before sending over.. same difference.. – Piotr Kula May 06 '11 at 19:31

7 Answers7

8

There is no cross platform way to accomplish this using only HTML/JavaScript. It is possible, however, using a very basic programmatic approach:

Step 1: Binding to Blur
Bind a "blur" event to your file input field, like so:

$("#input_field").blur(function(event){
    alert("Blur!");
});

Step 2: Server-Side Thumbnailing
You're going to have to write a small application/route on your server side application that simply accepts a form that contains in input file, and generates a temporary output file. You could even just temporarily store the filedata in your database, rather than write individual files to disk; the implementation is up to you. When this route receives a request, it should thumbnail the image, and then return a path to that thumbnail

Step 3: AJAX
First, choose one of the many available jQuery "AJAX Upload" libraries to make the form that contains your file upload it via AJAX. Apply that library to the form(For the examples below, I'll use ajaxForm.), and then modify your blur:

// AJAX the form
$("#your_form").ajaxForm({
    success: function(response){
        // Insert your returned thumbnail into your DOM.
    }
});

// Modify the blur
$("#input_field").blur(function(event){
    $("#input_field").closest("form").submit();
});

Issues:
There will be issues with the approach above. Making your form AJAX will mean submitting it regularly will break - not to mention that the thumbnail route will be different than the actual form submission route. Use some workarounds (for example, have a secondary hidden form, and the blur event copies the file-upload onto it, and then submits it).

Mike Trpcic
  • 25,305
  • 8
  • 78
  • 114
  • Yea this is the correct answer to the question- but like you mention it will break and will cause frustration. Any way the OP is trying todo what is already in Windows- the small/medium/large thumbnail views that appear in the OpenDialog Windows Form which supports multiple file selection. He is re-inventing the wheel. Good Answer! – Piotr Kula May 07 '11 at 08:45
  • Can u elaborate your solution little more like am new to this client side coding. – abhijit May 07 '11 at 12:06
  • What @Mike is proposing is actually as much server-side as client-side - this method uploads the images _before_ displaying thumbnails. – peteorpeter May 09 '11 at 02:37
5

This will not work in any other browser other than firefox because the FileReader object you are using is not a js standered, it is a class very specific to FireFox. As per web standard browser scripts(javascript) will not have security permission to read contents of any system resources(files).

In IE you can try to get some ActiveXObject(FileSystemObject) help access the file system contents.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I'm not sure, because I never tried it. It will always be better to not go against the defined standards. Still if you want to do this you will have to do different handlers for each browser you want to support. It will become a nightmare to support these changes in a longer period of time and with new different browser and versions of browsers coming out. – Arun P Johny May 02 '11 at 06:33
2

There's no cross-browser solution (even FileReader needs certain permissions in Firefox), only some workarounds for ie and firefox.

You should do the conventional way, upload the image to a temp file and delete/save it depending on user confirmation

Hope this helps

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
1

Try this for IE < 10:

<style type="text/css">
#imgPreview {
    width:320px;
    height:280px;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);
}
</style>

<h2>Preview images for MS-IE &lt; 10</h2>
<form id="form1" runat="server">
        <input type="file" onchange='document.getElementById("imgPreview").filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=this.value' />
        <div id="imgPreview"></div>
</form>

Fiddle: http://jsfiddle.net/Sme2L/5/

berniecc
  • 401
  • 4
  • 6
1

According to When can I use..., the File API is supported in Firefox 3.6+, Chrome 9+, Opera 11.1+ (and Safari 6).

If you really need this in IE, you may want to build a file uploader in Flash.

Jeffery To
  • 11,836
  • 1
  • 27
  • 42
  • +1 for suggesting me the when can i use site thanks a lot friend – abhijit May 09 '11 at 18:50
  • Safari 6? the current version is 5.1.7 – Vitim.us Jun 20 '12 at 15:31
  • @Vitim.us At the time of my answer, caniuse.com listed Safari 6.0 (the next major version of Safari known at the time) as having support for the File API. At this time, 5.1 and 5.2 (the near future release) is listed as having partial support (lacking FileReader support). – Jeffery To Jun 20 '12 at 15:58
  • For one moment I thought my Safari was outdated – Vitim.us Jun 22 '12 at 01:55
1

I concur with the nay-sayers who have already answered - local files are off limits by design.

But, if you are really committed to this preview-before-upload feature, and willing to include some bumpy UX, you might circumvent the local/server question and...

...use an accompanying AIR application to handle image uploading for your web app.

  • Create a simple AIR application that allow users to select local images and displays them in thumbnails without uploading them.

  • You can check to see if user's have the app installed, at which point you can prompt them to install or launch it if it's already installed (see here for more on that). You could allow them to opt out and use a fallback upload system without thumbnail previews as well.

  • Once the images are selected and reviewed (or even resized or otherwise processed), the AIR app could upload them to your server directly.

It's insane, I know, and probably doesn't fit your skill-set or expectations (based on the tags on this question) but I think it would work.

peteorpeter
  • 4,037
  • 2
  • 29
  • 47
1

Use jQuery ajax to solve your problem.

$.ajax({
    type: "post",
    url: "serverURL?randomParam="+(Math.random() * 1000),
    cache: false,               
    data: null,
    success: function(json){
        try{            
            var obj = JSON.parse(json);                                             
            if(obj[0].IMAGE!=null){                             
                $("#captchaImage").attr("src", obj[0].IMAGE); 
            }               
        }catch(e) {     
            showMessage("E1");  
        }
    },
    error: function(){
    }
});
Pang
  • 9,564
  • 146
  • 81
  • 122
Vicky
  • 9,515
  • 16
  • 71
  • 88