Styled input file button no longer shows chosen file

I’m using an Upload Script, and I’ve been working on trying to style the ‘Choose File Button’ (input file button)
which was a challenge to be styled for multiple browsers, but finally works with Google, IE and FF.

However, now that I’ve successfully styled the input file button, when a file is now chosen, the chosen file name no longer appears, prior to Submit.

I’ve attached an image of the code changes I made, plus some CSS styling, and this addition:

label input[type="file"] {
    position: fixed;
    top: -1000px;

Any suggestions/ideas/remedy on how to get the chosen file to show (or something to show an action has taken place) will be appreciated

I think it’s easier to use JS (JavaScript, not the same as Java) to create styled upload button.

All you need to do is to create button or another element, then you need to hide file input.
Then you need to add 'click event on button to imitate the same click on input and add ‘change’ event to input which will change button’s inner text to the value of the input.

There’s the demo: http://jsfiddle.net/YMMLQ/

Good luck!

Off Topic:

Yeah, that happened to me a lot :slight_smile:

HI,

That’s the problem with most of those css file-input hacks as you don’t get the filename displayed properly.

I tend to use a script like this that works much better and even allows for a button to remove the file.

There are other scripts around and work much better than any css methods because you are limited in what you can do CSS wise.

Edit:

Beaten to the post :slight_smile:

1 Like

Thanks for your replies.
I know there are many upload alternatives, but because this one works successfully, except for the file name being displayed, I’d prefer to find a solution for the Form I’m using, rather than substitute another one. This Form script I’m using has other attributes that I’d like to keep, which may not be available on other alternatives. Even if I can’t find a solution to show the file name, I’m also looking for ideas that could show something (if not a file name) to show that the file selection action has taken place. Currently, nothing appears once a file is chosen. Any ideas/suggestions will be appreciated.

Can you post your code on JSFiddle or CodePen or other sandbox service?

Because it’s would be easier to understand for us if you’ll upload code and show not only the code but also how it would be looked like.
P.S.: Are you using CI’s form validation?

Thanks for your message.

<?php
session_start();
require_once 'phps3integration_lib.php';
$message = "";
if (@$_POST['submit'] != "") {
    $allowed_ext = array("gif", "jpeg", "jpg", "png", "pdf", "doc", "docs", "zip", "mov", "MOV", "flv", "mp4", "3gp", "3GP");
    $extension = end(explode(".", $_FILES["file"]["name"]));
    if (($_FILES["file"]["size"] < 10485760000) && in_array($extension, $allowed_ext)) {
        if ($_FILES["file"]["error"] > 0) {
            //$message.="There is some error in upload, see: " . $_FILES["file"]["error"] . "<br>";//Enable this to see actual error
            $message.="There is some error in upload. Please try after some time.";
        } else {
            $uploaded_file = uploaded_file_to_s3($_FILES["file"], "uploads", true);
            if ($uploaded_file != FALSE) {
                $user_name = @$_POST['user_name'] != "" ? @$_POST['user_name'] : "Anonymous";
                $form_data = array(
                    'file' => $uploaded_file,
                    'user_name' => $user_name,
                    'type' => 'file'
                );
                mysql_query("INSERT INTO `phps3files` (`id`, `file`, `user_name`, `type`) VALUES (NULL, '" . $uploaded_file . "', '" . $user_name . "', 'file')") or die(mysql_error());
                $message.= "File Successfully Uploaded";
            } else {
                $message.="There is some error in upload. Please try after some time.";
            }
        }
    } else {
        $message.= "Invalid file, Please upload a gif/jpeg/jpg/png/pdf/doc/docs/zip/mov/flv/mp4/3gp file of maximum size 5 MB.";
    }
}
?>

<?php
require_once 'header.php';
?>
<head>
<style>
label input[type="file"] {
    position: fixed;
    top: -500px;
}

.myLabel {
	width: 100px;
	height: 50px;
    border: 1px solid #800000;
    border-radius: 4px;
    padding: 2px 5px;
    margin: 12px 2px 2px 2px;
    background: #fff;
    display: inline-block;
}
.myLabel:hover {
    background: #fff;
}
.myLabel:active {
    background: #CCF;
}
</style>

<style>
.myLabel1 {
	width: 178px;
	height: 60px;
    border: 1px solid #;
    border-radius: ;
    padding: 2px 5px;
    margin: 12px 2px 2px 2px;
    background: #fff000;
    background-image:url('/images/upload.png');

}
.myLabel1:hover {
    background-image:url('/images/upload.png');
}
.myLabel1:active {
    background: #CCF;
}
</style>

</head>
<html>
<br /><br /><br />

<font size="6" color="#c53800"><b>Upload:</b></font><br /><br />
<fieldset>
<form action="" method="post" enctype="multipart/form-data">

<div class="control-group">
<label for="file" class="control-label"><font size="6" color="#454545"><b>Choose a file to upload:</b></font></label>

<div class='controls'>
<label class="myLabel">
<input id="file" type="file" name="file" />
Choose File
</label>
<?php //echo form_error('file');   ?> </div>
</div>


<div class="control-group">
<div class='controls'>
<label class="myLabel1">
<input type="submit" name="submit" value="Submit" class="btn" style="opacity: 0">
</label>
</div>
</form>
</fieldset>

<?php
if ($message != "" || @$_SESSION['message'] != "") {
    ?>
    <div class="alert alert-success">
        <?php echo $message; ?>     
        <?php
        echo @$_SESSION['message'];
        @$_SESSION['message'] = '';
        ?>
    </div>
    <?php
}
?>
<div>
</div>

<?php require_once 'footer.php'; ?>

I don’t know what CI’s form validation is

Is that suppose to look like this: http://jsfiddle.net/Kt4g9/
How I understand you want to display form’s file input, right?

label input[type="file"] {
    position: fixed;
    top: -500px;
}

Makes your file input shift out of the screen.

Look at this:

The input is one the place and the button is there.
If it’s not what you want, reply back with quote.

Good luck!

Thanks for your reply.
Yes it’s supposed to look like that http://jsfiddle.net/Kt4g9/ except with all the functionality of this: http://jsfiddle.net/Kt4g9/1/
And by all the functionality, I mean having the ‘no file chosen’ appear and then a file name appear.
I’m trying to simply make it look better than this: see image
But I’d like to keep the ‘no file chosen’ and subsequently the file name to appear, once a file is selected.

It seems kind of impossible without JS. File inputs very hard to style, or I would say even impossible with CSS. The only solution, I can think of, is using simple JS code.

I know it sometimes happens when you want to do something in CSS only for Graceful Degradation, but not everything can done in CSS.

Browsers purposefully make inputs near impossible to style due to it affecting user experience. Your best bet would probably be to just use a <button> and use JS to make it behave. For those without JS, you could have a default plain <input>.

That’s exactly what my first demo is doing:

There’s the demo: http://jsfiddle.net/YMMLQ/

Thanks for all the replies.
At this point then, maybe someone can simply help me do one of the following:

  • Get the value of the file selected and just add that to a div next to the styled input file button.
  • Capture the file name from the DOM once the file is selected and then write it to a another HTML element located at the same spot
  • Have a simple a message appear, once a file is selected that says “File Selected”
    just so the uploader knows that an action has taken place, prior to submit.
    Any help with one of these, or another suggestion, will be welcomed.
    Much thanks again

Maybe something like that?: http://jsfiddle.net/4RvDA/

Thanks for the reply.
Although I’m not completely sure where to put the code, I tried adding the code, but got this upon upload:

Notice: Undefined index: file in /home/public_html/upload_file.php on line 7

Notice: Undefined index: file in /home/public_html/upload_file.php on line 8

which are:

$allowed_ext = array(“gif”, “jpeg”, “jpg”, “png”, “pdf”, “doc”, “docs”, “zip”, “mov”, “flv”, “mp4”, “3gp”);
$extension = end(explode(“.”, $_FILES[“file”][“name”]));

And i’m also not sure how your code styles the Choose File button.
Any additional help will be appreciated

That’s because I didn’t used name attribute inside of input. Just add to your input ‘name=“file”’:

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

That won’t work in Firefox I’m afraid as innerText isn’t supported. You would need textContent I believe (IE9+).


obj.message.textContent  = this.value;

Or innerHTML I suppose but js is not my thing :slight_smile:

And i’m also not sure how your code styles the Choose File button.

You just style the replaced button element as you want.

Based mostly on volter9’s code something like this:


<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
#message {
	padding: 10px;
	display: inline-block;
}
#button {
	background:red;
	border-radius :10px;
	border:1px solid #ccc;
	padding:5px 15px;
	box-shadow:3px 3px 30px rgba(0,0,0,0.3);
	display: inline-block;
	outline:0;
}
#button:hover, #button:focus {
	background:#000;
	color:#fff;
}
</style>
</head>

<body>
<input id="input" type="file" />
<button id="button">Click to select file</button>
<div id="message">No file chosen</div>
<script>
// 'cause I'm lazy
var ids = ['input', 'message', 'button'];
var obj = {};

ids.forEach(function (v) {
    obj[v] = document.getElementById(v);
});

obj.input.style.display = 'none';
obj.button.style.display = 'inline-block';

obj.input.addEventListener('change', function () {
    var filename = this.value.replace(/^.*[\\\\\\/]/, '');
		obj.message.innerHTML  = filename;
    obj.message.style.display = 'inline-block';
});

obj.button.addEventListener('click', function (e) {
    e.preventDefault();
    
    obj.input.click();
});

</script>
</body>
</html>

I removed the fakepath description because that will scare users no end (it did me :)) and it will also make sure that the text doesn’t spill right over the page with incredibly long paths.

Of course as I said at the beginning there are many plugins around that take care of all the browsers differences for you if you want older support.

Sorry, my fault. Didn’t knew which browser TP was using.
The only thing I want to suggest in this topic:

You need to practice in organizing your code. Your code looks like spaghetti code.
Try CodeIgniter framework for beginning.

Thanks for all the replies. I added the Paul O’b code and it works successfully in Google (thanks),
But in IE the “click to select file” button doesn’t do anything. To upload a file the browse button,
apparently needs to be selected. If there is some coding to fix that, I’d be interested in heariung about it.
see attached image files
Thanks again. I look forward to any additional assistance.
Google: IE:

The <input> needs to be changed to this

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

Both browsers behave now on my end :).

Thanks for your reply/help.
When I change the line to this:

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

I get this:

Notice: Undefined index: file in /home/public_html/upload_file.php on line 7
Notice: Undefined index: file in /home/public_html/upload_file.php on line 8

Those lines 7 & 8 are:

$extension = end(explode(".", $_FILES["file"]["name"]));
    if (($_FILES["file"]["size"] < 10485760000) && in_array($extension, $allowed_ext)) {

When I make the line this:

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

Those Notices disappear. However, the issue remains the same in IE, which is that the “click to select file” button doesn’t do anything(that I can see), and to upload a file the Browse button, needs to be selected.

And it still looks like this - see IE-image in previous post.
Someone suggested this:
“with JavaScript or Jquery… Create an event handler that if a file is selected $(‘.selectedfile’).show(); <span class=“selectedfile”>Your File has been Chosen for Upload!</span> then once the submit button has been hit you could also swap that out for a loader gif or something”. But I don’t know how to do that.

Any additional help will be welcomed.
Much thanks again.