• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 360
  • Last Modified:

input file requires an extra click in IE

My html file upload routine opens to your documents immediately in Firefox, but in IE you have to click the "Browse" button once to sort of announce your presence, after which you can click it again and open the file dialog.

It is built in php by echo '<input type="file" size="25" name="image_name" />';

Any suggestions about how to solve this in IE?
0
Glen Gibb
Asked:
Glen Gibb
  • 8
  • 8
1 Solution
 
Rajesh DalmiaCommented:
it's not this control... seems to be something else exists.... can u post the total form code
0
 
Ray PaseurCommented:
And how is this a problem?  

Any file upload will require the client to choose the file.  The browsers may "remember" the location of the last upload and automatically start in that directory.  From the HTML and server-side you have zero control over this -- it is both browser-dependent (since the client may have uploaded a file to another web site recently) and a security issue (you cannot prepopulate the variables for input type=file).

In short, it's working the way it is supposed to work.  Regards, ~Ray
0
 
Glen GibbAuthor Commented:
For Ray:

A quick note of explanation.  It's not a case of opening to a default folder.  It's a case of opening the file dialog.

A novice user expects something to happen when she clicks a button.  In this case, the click does nothing -- the dialog does not open.  

It requires a second click off the button to open the dialog.  This is unusual behavior.and would certainly be confusing to a new user (an old one, too, maybe.)

For rdonline1:

See the html/php code attached:
<form enctype="multipart/form-data" action="addImage.php" method="post">

		<br/>

		<label for="file">Please choose an image to upload:</label>

		<input type="file" name="file" size="40" id="file"/>

		<br/><br/>

		<input type="hidden" name="ID" value="<?=$_GET["ID"]?>"/>

		<input type="submit" name="submit" value="Upload" />

	</form>

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Ray PaseurCommented:
I'm not seeing any unusual symptom.  I ran the exact script posted above on both FF3 and IE8.  Identical behavior, the file upload dialog opened immediately, except that IE started showing me files in a different directory (the desktop) whereas FF started showing me files in the last folder I had used for uploads.

In semi-related news, there is a well-documented process for doing PHP file uploads.  Please look over this script.  It implements most of the current recommendations and some of its features (MAX_FILE_SIZE, for one) may be helpful to you.

Best regards, ~Ray
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php
// http://docs.php.net/manual/en/function.getimagesize.php


// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'uploads';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT
$max_file_size = '8192000';  // EIGHT MEGABYTE LIMIT ON UPLOADS

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
    -->

    <form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
    <input type="submit" name="_submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else 
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    //    echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code    = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file = getcwd() . '/' . $uploads . '/' . $f_name . '.' . $f_type;
        $my_file     =                  $uploads . '/' . $f_name . '.' . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }
        
        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

0
 
Ray PaseurCommented:
'Nother thought... What OS are you looking at?  I tested on XP.  Can test tomorrow on Windows 7.  Nobody uses Vista, so I did not test that.
0
 
Glen GibbAuthor Commented:
Thanks for your input, Ray.

This is a strange phenomenon.  I have a friend who tried the site in IE8 and had no problem whatsoever.  

The code looks fine.  FF works great.  

IE is problematic.  Have used XP, and Win7 OS's and both behaved identically.  Tried it from a Win7 machine in a distant city, and it also (mis)behaves the same.

Would you email me?  My address is capt_coaldale@yahoo.ca.  I'll supply a username and password to the site, so you can view the page live if it would be useful.

If push comes to shove, I have a section on "Making an AJAX-Style File Upload" in a Wrox text I just purchased.  This routine may prove more cross-browser friendly.
0
 
Glen GibbAuthor Commented:
I think this is a CSS issue.  

I fixed a number of CSS warnings that cropped up in FireFox.  Then, for a moment, IE seemed to behave as it should have.   Next time I opened IE, it was misbehaving again.

Any ideas on how to debug IE?

 
0
 
Ray PaseurCommented:
You can find my public profile, including email address here:
http://www.experts-exchange.com/M_3774417.html

I'll email you, too.
0
 
Glen GibbAuthor Commented:
IE tells me there is a JS error with "e.target" in this file.  (Whether this is part of the problem or not, time will tell.)  


// onload event ...
window.onload = init;

function init()
{
	stripeTable.getTheTables();
	//setupHilites("textarea");
	//setupHilites("select");
	//setupHilites("input");
}

function setupHilites( thisTag )
{
	var theInputs = document.getElementsByTagName(thisTag);
	var inputCount = theInputs.length;
	for (i=0; i < inputCount; i++)
	{
		addEvent(theInputs[i], 'focus', checkHilite);
		addEvent(theInputs[i], 'blur', checkHilite);
	}
}

function addEvent(obj, type, fn)
{
	if ( obj.attachEvent )
	{
		obj['e' + type + fn] = fn;
		obj[type + fn] = function() {obj['e' + type + fn] ( window.event );}
		obj.attachEvent ( 'on' + type, obj[type + fn] );
	}
	else
		obj.addEventListener(type, fn, false);
}

function checkHilite(e)
{
	switch(e.type)
	{
		case "focus":
			e.target.className = "hilite";
			break;
		case "blur":
			e.target.className = "";
			break;
	}
}

Open in new window

0
 
Glen GibbAuthor Commented:
Whoops!  Forgot that the calls had been commented in the Init(), but that was temporary.
0
 
Ray PaseurCommented:
OK, I signed in and followed the links to the place to upload an image.  The upload form, in its entirety but stripped of the irrelevant parts, is in the code snippet.  My browser (FF3) spent an amazing amount of time waiting for something from http://mobiusrobot.com/  Then eventually this wound up in the DOM (but not on the screen)

Failed to load source for: http://mobiusrobot.com/liveViewer/live.php?userID=3047781&UserTime=2010-08-30%2016%3A50%3A01&username=undefined&WindowSize=1680x530&TimePage=0&LoadTime=&ClickXY=805x299&Domain=simpletek.biz&ScreenResolution=1680x1050&Page=http%3A//simpletek.biz/gps/homeback/addImage.php%3FID%3D385&Referrer=http://simpletek.biz/gps/homeback/result.php?ID=385

In a moment I will post a script that shows you how to upload an image.
<form enctype="multipart/form-data" action="addImage.php" method="post">
<input type="file" name="file" size="40" id="file"/>
<input type="hidden" name="ID" value="385"/>
<input type="submit" name="submit" value="Upload" />
</form>

Open in new window

0
 
Ray PaseurCommented:
How to upload an image file with HTML and PHP.   Bonus: How to resize the images!

Best regards, ~Ray
<?php // RAY_upload_and_resize_image.php


// UPLOAD AN IMAGE AND RESIZE IT TO FIT A PREDEFINED SIZE


// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{

// IS GD INSTALLED AT ALL?
   if (!function_exists("gd_info"))
   {
      if ($display) echo "<br/>GD NOT INSTALLED\n";
      return FALSE;
   }

// IF GD IS INSTALLED GET DETAILS
   $gd = gd_info();

// IF DISPLAY IS REQUESTED, PRINT DETAILS
   if ($display)
   {
      echo "<br/>GD DETAILS:\n";
      foreach ($gd as $key => $value)
      {
         if ($value === TRUE)  $value = 'YES';
         if ($value === FALSE) $value = 'NO';
         echo "<br/>$key = $value \n";
      }
   }

// RETURN THE VERSION NUMBER
   $gd_version = preg_replace('/[^0-9\.]/', '', $gd["GD Version"]);
   return $gd_version;
}


// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE, OR FALSE IF NO RESIZE NEEDED
function create_right_size_image($image, $width=720)
{
// IS GD HERE?
   $gdv = get_gd_info();
   if (!$gdv) return FALSE;

// GET AN IMAGE THING
   $source = imagecreatefromjpeg("$image");

// GET THE X AND Y DIMENSIONS
   $imageX = imagesx($source);
   $imageY = imagesy($source);

// IF NO RESIZING IS NEEDED
   if ($imageX <= $width)
   {
      return FALSE;
   }

// THE WIDTH IS TOO GREAT - MUST RESIZE
   $tnailX = $width;
   $tnailY = (int) (($tnailX * $imageY) / $imageX );

// WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
   if ($gdv >= 2)
   {
// IF GD IS AT LEVEL 2 OR ABOVE
      $target = imagecreatetruecolor($tnailX, $tnailY);
      imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   } else
   {
// IF GD IS AT A LOWER REVISION LEVEL
      $target = imagecreate($tnailX, $tnailY);
      imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   }
   return $target ;
}
/* ********************************************************************************************* */


// ESTABLISH THE NAME OF THE PHOTOS DIRECTORY
$photos    = 'photos';

// ESTABLISH THE LARGEST FILE WE WILL UPLOAD
$max_file_size = '5000000'; // A BIT MORE THAN 4MB

// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;

// IF THERE IS NOTHING USEFUL IN $_POST, PUT UP THE FORM FOR INPUT
if ( (empty($_POST['p'])) && (empty($_POST['MAX_FILE_SIZE'])) ) {
    ?>
    <h2>Upload Photos</h2>

    <!-- NOTE THE USE OF ENCTYPE -->
    <form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
    <input type="hidden" name="p" value="1" />
    <!-- MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD -->
    <input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
    <!-- INPUT NAME= IN TYPE=FILE DETERMINES THE NAME FOR ACTION SCRIPT TO USE IN $_FILES ARRAY -->
    <p>
    Find the photo you want to upload and click the "Upload" button below.
    </p>

    <table cellpadding="1" cellspacing="1" border="0">
    <tr><td align="right"><span class="required">Photo: </span></td> <td><input name="userfile" type="file" size="80" /></td></tr>
    <tr><td> </td><td><input type="submit" name="_submit" value="Upload" />
    &nbsp; &nbsp; Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> an existing photo.</td></tr>
    </table>
    </form>
    <?php

    die();

} else {

// THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: Upload Photos</h2>\n";
    echo "<p>\n";

// SYNTHESIZE THE NEW FILE NAME
    $f_type  = trim(strtolower(end    (explode( '.', basename($_FILES['userfile']['name'] )))));
    $f_name  = trim(strtolower(current(explode( '.', basename($_FILES['userfile']['name'] )))));
    $my_new  = getcwd() . '/' . $photos . '/' . $f_name . '.' . $f_type;
    $my_file = $photos  . '/' . $f_name . '.' . $f_type;

// TEST FOR ALLOWABLE EXTENSIONS
    if ($f_type != 'jpg')
    {
       die('Sorry, only JPG files allowed');
    }

// IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code != 0)
    {
        $error_message = $errors[$error_code];
        echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
        die('Sorry');
    }

// MOVE THE FILE INTO THE DIRECTORY
    $overwrite    = $_POST['overwrite'];
    $file_size    = number_format($_FILES["userfile"]["size"]);

// IF THE FILE IS NEW
    if (!file_exists($my_new))
    {
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
        {
            $upload_success = 1;
        } else
        {
            $upload_success = -1;
        }

// IF THE FILE ALREADY EXISTS
    } else
    {
        echo "<b><i>$my_file</i></b> already exists.\n";

// SHOULD WE OVERWRITE THE FILE? IF NOT
        if (empty($overwrite))
        {
            $upload_success = 0;

// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
        } else
        {
            $now    = date('Y-m-d');
            $my_bak = $my_new . '.' . $now . '.bak';
            if (!copy($my_new, $my_bak))
            {
                echo "<b>Attempted Backup Failed!</b>\n";
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
            {
                $upload_success = 2;
            } else
            {
                $upload_success = -1;
            }
        }
    }

// REPORT OUR SUCCESS OR FAILURE
    if ($upload_success == 2) { echo "It has been overwritten.\n"; }
    if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
    if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }

    if ($upload_success > 0)
    {
        echo "$file_size bytes uploaded.\n";
        chmod ($my_new, 0755);
    }

    echo "</p>\n";

// RESIZE THE FILE TO FIT PAGE WIDTH, IF NECESSARY
    if ($upload_success > 0)
    {
        if ($imageblob = create_right_size_image($my_new))
        {
            imagejpeg($imageblob, $my_new);
        }
    }

    echo "<p><a href=\"$my_file\">See the file</a></p>\n";
}

Open in new window

0
 
Glen GibbAuthor Commented:
The Mobius Robot is a cool viewer that tracks the site usage.  

However, if the user is waiting forever, perhaps I'll set this feature aside.

I've been working on the code, so perhaps we've been at cross purposes!

The code snippet is golden!  I've been hosting the site on my own system while the "real" host adds GD support to his system -- it's a long story.

Thanks for much help.

Capt
0
 
Glen GibbAuthor Commented:
Thanks for going the extra mile.
0
 
Ray PaseurCommented:
You might want to contact Nick Gilbert at ChiHost.  I host a number of sites there.  EXCELLENT tech support and near flawless dependability.  

1-800-955-2841
http://www.chihost.com/

No waiting, and no long stories!

In semi-related news, Google Analytics is what most of us use to track site usage.
0
 
Glen GibbAuthor Commented:
Turns out the extra click is part of the Image-Label-Focus bug in IE.

<img> elements that are inside <label> elements, when clicked, do not cause the focus to be transfered to corresponding form control.

See "http://haslayout.net/css/Image-Label-Focus-Bug" for a workaround.

Capt
0
 
Ray PaseurCommented:
thanks again, Microsoft!

;-)

~Ray
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 8
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now