<input type="file" value="Browse" name="avatar" id="id_avatar" />
I tried to modify the value
, but it’s not working. How to customize the button text?
BalusC
1.1m370 gold badges3586 silver badges3540 bronze badges
asked Dec 22, 2009 at 5:07
user198729user198729
60.6k107 gold badges250 silver badges346 bronze badges
4
Use Bootstrap FileStyle, which is used to style the file fields of forms. It is a plugin for a jQuery-based component library called Twitter Bootstrap
Sample usage:
Include:
<script type="text/javascript" src="js/bootstrap-filestyle.min.js"> </script>
Via JavaScript:
$(":file").filestyle();
Via data attributes:
<input type="file" class="filestyle" data-classButton="btn btn-primary" data-input="false" data-classIcon="icon-plus" data-buttonText="Your label here.">
answered Sep 20, 2013 at 4:57
Fernando KoshFernando Kosh
3,3321 gold badge35 silver badges30 bronze badges
8
Hide the file input. Create a new input to capture a click event and forward it to the hidden input:
<input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file"/>
2540625
10.7k8 gold badges49 silver badges56 bronze badges
answered Mar 27, 2016 at 13:58
11
You can put an image instead, and do it like this:
HTML:
<img src="/images/uploadButton.png" id="upfile1" style="cursor:pointer" />
<input type="file" id="file1" name="file1" style="display:none" />
JQuery:
$("#upfile1").click(function () {
$("#file1").trigger('click');
});
CAVEAT:
In IE9 and IE10 if you trigger the onClick in a file input via javascript, the form will be flagged as ‘dangerous’ and cannot be submitted with javascript, not sure if it can be submitted traditionally.
Charlie74
2,89714 silver badges23 bronze badges
answered Dec 29, 2011 at 11:58
ParParParPar
7,2277 gold badges43 silver badges54 bronze badges
6
The «upload file…» text is pre-defined by the browser and can’t be changed.
The only way to get around this is to use a Flash- or Java-based upload component like swfupload.
answered Dec 22, 2009 at 5:11
PekkaPekka
438k140 gold badges968 silver badges1083 bronze badges
3
Works Perfectly on All Browsers Hope it will work for you too.
HTML:
<input type="file" class="custom-file-input">
CSS:
.custom-file-input::-webkit-file-upload-button {
visibility: hidden;
}
.custom-file-input::before {
content: 'Select some files';
display: inline-block;
background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);
border: 1px solid #999;
border-radius: 3px;
padding: 5px 8px;
outline: none;
white-space: nowrap;
-webkit-user-select: none;
cursor: pointer;
text-shadow: 1px 1px #fff;
font-weight: 700;
font-size: 10pt;
}
.custom-file-input:hover::before {
border-color: black;
}
.custom-file-input:active::before {
background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);
}
Change content: 'Select some files';
with the text you want within ''
IF NOT WORKING WITH firefox then use this instead of input:
<label class="custom-file-input" for="Upload" >
</label>
<input id="Upload" type="file" multiple="multiple" name="_photos" accept="image/*" style="visibility: hidden">
answered Oct 3, 2015 at 6:32
Code BlackCode Black
5305 silver badges11 bronze badges
11
Simply
<label class="btn btn-primary">
<i class="fa fa-image"></i> Your text here<input type="file" style="display: none;" name="image">
</label>
[Edit with snippet]
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<label class="btn btn-primary">
<i class="fa fa-image"></i> Your text here<input type="file" style="display: none;" name="image">
</label>
answered Oct 31, 2018 at 4:59
Ken KarloKen Karlo
4664 silver badges5 bronze badges
1
I think this is what you want:
<button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>
<input type='file' id="getFile" style="display:none">
answered Dec 23, 2017 at 7:05
ChitChit
2952 silver badges12 bronze badges
1
This is a JQuery plugin to change the button text of an input file element.
Example HTML:
<input type="file" id="choose-file" />
Example JS:
$('#choose-file').inputFileText({
text: 'Select File'
});
Result:
answered Jun 26, 2015 at 0:35
datchungdatchung
3,13624 silver badges24 bronze badges
1
<input id="uploadFile" placeholder="Choose File" disabled="disabled" />
<div class="fileUpload btn btn-primary">
<span>Your name</span>
<input id="uploadBtn" type="file" class="upload" />
</div>
JS
document.getElementById("uploadBtn").onchange = function () {
document.getElementById("uploadFile").value = this.value;
};
more http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/
Igor Ivancha
3,3854 gold badges31 silver badges39 bronze badges
answered Dec 11, 2014 at 10:49
webskywebsky
3,0221 gold badge34 silver badges31 bronze badges
0
Use <label>
for the caption
<form enctype='multipart/form-data' action='/uploads.php' method=post>
<label for=b1>
<u>Your</u> caption here
<input style='width:0px' type=file name=upfile id=b1
onchange='optionalExtraProcessing(b1.files[0])'
accept='image/png'>
</label>
</form>
This works without any javascript. You can decorate the label to any degree of complexity, to your heart’s content. When you click on the label, the click automatically gets redirected to the file input. The file input itself can be made invisible by any method. If you want the label to appear like a button, there are many solutions, e.g.:
label u {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: initial;
}
answered Sep 12, 2016 at 18:37
MKaamaMKaama
1,6242 gold badges18 silver badges26 bronze badges
I know, nobody asked for it but if anybody is using bootstrap, it can be changed through Label and CSS Pseudo-selector.
For changing button text:
.custom-file-label::after {
content: "What's up?";
}
For changing field text:
<label class="custom-file-label" for="upload">Drop it like it's hot</label>
Here’s a fiddle.
answered Jul 14, 2020 at 7:55
In Addition to MushyPeas answer, you can add a label to show the filename like so (no jQuery needed):
Credits also to this answer.
<input type="button" id="click-input" value="Write anything" onclick="document.getElementById('file').click();" />
<label for="click-input" id="file-name">Bla bla</label>
<input type="file" style="display:none;" id="file">
<script>
inputElement = document.getElementById('file')
labelElement = document.getElementById('file-name')
inputElement.onchange = function(event) {
var path = inputElement.value;
if (path) {
labelElement.innerHTML = path.split(/(\|/)/g).pop()
} else {
labelElement.innerHTML = 'Bla bla'
}
}
</script>
answered Sep 30, 2021 at 20:48
monty.pymonty.py
2,3791 gold badge15 silver badges28 bronze badges
Only CSS & bootstrap class
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="col-md-4 input-group">
<input class="form-control" type="text" />
<div class="input-group-btn">
<label for="files" class="btn btn-default">browse</label>
<input id="files" type="file" class="btn btn-default" style="visibility:hidden;" />
</div>
</div>
isherwood
56.5k16 gold badges109 silver badges151 bronze badges
answered Aug 8, 2018 at 8:58
EDIT: I see now by the comments that you are asking about the button text, and not the file path. My bad. I’ll leave my original answer below in case someone else who stumbles upon this question interprets it the way I originally did.
2nd EDIT: I had deleted this answer because I decided that I misunderstood the question and my answer was not relevant. However, comments in another answer indicated that people still wanted to see this answer so I’m undeleting it.
MY ORIGINAL ANSWER (I thought the OP was asking about the path, not the button text):
This is not a supported feature for security reasons. The Opera web browser used to support this but it was removed. Think about what would be possible if this were supported; You could make a page with a file upload input, pre-populate it with a path to some sensitive file and then auto-submit the form using javascript triggered by the onload
event. This would happen too fast for the user to do anything about it.
answered Dec 22, 2009 at 5:11
AsaphAsaph
157k25 gold badges193 silver badges197 bronze badges
In Bootstrap +4.5 you can simply add this to your code:
.custom-file-input~.custom-file-label::after {
content: "Your custom text ...";
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="custom-file">
<input type="file" class="custom-file-input">
<label class="custom-file-label">Your custom placeholder ...</label>
</div>
isherwood
56.5k16 gold badges109 silver badges151 bronze badges
answered Aug 27, 2020 at 23:01
What about icons without using real images and «interactivity»?
Check the following example that doesn’t use any image, not even javascript, and also it is interactive in the sense that changes its look on mouse events as on mouse-over and on mouse left or right click.
input
{
padding: 10px;
width: 100%;
}
input::file-selector-button
{
display: none;
}
input::before
{
border: 1px solid red;
border-radius: 3px 8px 3px 8px;
color: red;
content: attr(value)' Some more text';
margin: 25px;
padding: 5px;
}
input:hover:before
{
border: 1px groove blue;
background: lime;
}
input:active:before
{
border: 1px groove blue;
background: yellow;
}
<input type="file" value="📂 Open..." />
How it works:
Basically, it hides the main button of the standard file input element and shows its pseudo element, indicated by the :before part. Than it styles how it looks like and also some mouse events, so it is kind of «interactive».
Also using the :file-selector-button pseudo-element, allows to style the button it self or even to not display it at all as I have done int the above example with the code display: none;. This allows to use the :before element as replacement of the button.
The advantage of doing it with css is that by not using any javascript it will work even if the user’s browser has javascript disabled.
About the folder icon:
Actually it is a char it self in UNICODE: 📂 that is U+1F4C2 code-point. To see it correctly the user of the page must have a font that supports it. I did not install any new font into my system (Win7) and I see it correctly: so I suppose it is correctly seen by everyone else.
answered Sep 2, 2022 at 14:10
willy wonkawilly wonka
1,3201 gold badge17 silver badges29 bronze badges
Here is a way to «change» the text of an input with file type, with pure HTML and javascript:
<input id='browse' type='file' style='width:0px'>
<button id='browser' onclick='browse.click()'>
*The text you want*
</button>
Wai Ha Lee
8,41977 gold badges60 silver badges90 bronze badges
answered Apr 14, 2019 at 20:44
IntelarXIntelarX
1211 silver badge4 bronze badges
- Before that
<input type="file">
, add an image and<input style="position:absolute">
it will occupy the space of<input type="file">
-
Use the following CSS to the file element
position:relative; opacity:0; z-index:99;
Toby Speight
26.2k47 gold badges64 silver badges98 bronze badges
answered Jul 11, 2013 at 5:58
0
You can simply add some css trick. you don’t need javascript or more input files and i keep existing value attribute. you need to add only css. you can try this solution.
.btn-file-upload{
width: 187px;
position:relative;
}
.btn-file-upload:after{
content: attr(value);
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 48%;
background: #795548;
color: white;
border-radius: 2px;
text-align: center;
font-size: 12px;
line-height: 2;
}
<input type="file" class="btn-file-upload" value="Uploadfile" />
answered Mar 7, 2019 at 5:08
Udara KasunUdara Kasun
2,14316 silver badges25 bronze badges
for me it does not work the custom text with bootstrap-filestyle. It help with button decoration but text its weird to be changed, before get into wrestling with css i try the following :
$( document ).ready(function() {
$('.buttonText').html('Seleccione ficheros');
});
bootstrap-filestyle render the component as span with a class named butonText, so when document load just change the text. easy right and it must work on all browsers.
cheers
answered Apr 22, 2019 at 9:04
if you using rails and have problem apply it, I would like to add some tips from original answer posted by @Fernando Kosh
- Download file zip and copy file bootstrap-filestyle.min.js ke folder app/assets/javascripts/
-
open your application.js and add this line below
//= require bootstrap-filestyle.min
-
open your coffee and add this line
$(«:file»).filestyle({buttonName: «btn-primary»,buttonBefore: true,buttonText: » Your text here»,icon: false});
answered Mar 20, 2017 at 15:20
widjajaydwidjajayd
5,9423 gold badges29 silver badges39 bronze badges
I did it like this for my project:
.btn-outlined.btn-primary {
color: #000;
}
.btn-outlined.btn-primary:active, .btn-outlined.btn-positive:active, .btn-outlined.btn-negative:active {
color:#000;
}
.btn-block {
display: block;
width: 100%;
padding: 15px 0;
margin-bottom: 10px;
font-size: 18px;
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
<label for="fileUpload" class="btn btn-primary btn-block btn-outlined">Your text</label>
<input type="file" id="fileUpload"style="display: none;">
answered Apr 6, 2020 at 7:50
KhapiKhapi
5204 silver badges7 bronze badges
This is an alternative solution that may be of help to you. This hides the text that appears out of the button, mixing it with the background-color of the div. Then you can give the div a title you like.
<div style="padding:10px;font-weight:bolder; background-color:#446655;color: white;margin-top:10px;width:112px;overflow: hidden;">
UPLOAD IMAGE <input style="width:100px;color:#446655;display: inline;" type="file" />
</div>
Kaiido
116k11 gold badges201 silver badges258 bronze badges
answered Jun 15, 2013 at 4:49
2
<input type="file" value="Browse" name="avatar" id="id_avatar" />
I tried to modify the value
, but it’s not working. How to customize the button text?
BalusC
1.1m370 gold badges3586 silver badges3540 bronze badges
asked Dec 22, 2009 at 5:07
user198729user198729
60.6k107 gold badges250 silver badges346 bronze badges
4
Use Bootstrap FileStyle, which is used to style the file fields of forms. It is a plugin for a jQuery-based component library called Twitter Bootstrap
Sample usage:
Include:
<script type="text/javascript" src="js/bootstrap-filestyle.min.js"> </script>
Via JavaScript:
$(":file").filestyle();
Via data attributes:
<input type="file" class="filestyle" data-classButton="btn btn-primary" data-input="false" data-classIcon="icon-plus" data-buttonText="Your label here.">
answered Sep 20, 2013 at 4:57
Fernando KoshFernando Kosh
3,3321 gold badge35 silver badges30 bronze badges
8
Hide the file input. Create a new input to capture a click event and forward it to the hidden input:
<input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file"/>
2540625
10.7k8 gold badges49 silver badges56 bronze badges
answered Mar 27, 2016 at 13:58
11
You can put an image instead, and do it like this:
HTML:
<img src="/images/uploadButton.png" id="upfile1" style="cursor:pointer" />
<input type="file" id="file1" name="file1" style="display:none" />
JQuery:
$("#upfile1").click(function () {
$("#file1").trigger('click');
});
CAVEAT:
In IE9 and IE10 if you trigger the onClick in a file input via javascript, the form will be flagged as ‘dangerous’ and cannot be submitted with javascript, not sure if it can be submitted traditionally.
Charlie74
2,89714 silver badges23 bronze badges
answered Dec 29, 2011 at 11:58
ParParParPar
7,2277 gold badges43 silver badges54 bronze badges
6
The «upload file…» text is pre-defined by the browser and can’t be changed.
The only way to get around this is to use a Flash- or Java-based upload component like swfupload.
answered Dec 22, 2009 at 5:11
PekkaPekka
438k140 gold badges968 silver badges1083 bronze badges
3
Works Perfectly on All Browsers Hope it will work for you too.
HTML:
<input type="file" class="custom-file-input">
CSS:
.custom-file-input::-webkit-file-upload-button {
visibility: hidden;
}
.custom-file-input::before {
content: 'Select some files';
display: inline-block;
background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);
border: 1px solid #999;
border-radius: 3px;
padding: 5px 8px;
outline: none;
white-space: nowrap;
-webkit-user-select: none;
cursor: pointer;
text-shadow: 1px 1px #fff;
font-weight: 700;
font-size: 10pt;
}
.custom-file-input:hover::before {
border-color: black;
}
.custom-file-input:active::before {
background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);
}
Change content: 'Select some files';
with the text you want within ''
IF NOT WORKING WITH firefox then use this instead of input:
<label class="custom-file-input" for="Upload" >
</label>
<input id="Upload" type="file" multiple="multiple" name="_photos" accept="image/*" style="visibility: hidden">
answered Oct 3, 2015 at 6:32
Code BlackCode Black
5305 silver badges11 bronze badges
11
Simply
<label class="btn btn-primary">
<i class="fa fa-image"></i> Your text here<input type="file" style="display: none;" name="image">
</label>
[Edit with snippet]
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<label class="btn btn-primary">
<i class="fa fa-image"></i> Your text here<input type="file" style="display: none;" name="image">
</label>
answered Oct 31, 2018 at 4:59
Ken KarloKen Karlo
4664 silver badges5 bronze badges
1
I think this is what you want:
<button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>
<input type='file' id="getFile" style="display:none">
answered Dec 23, 2017 at 7:05
ChitChit
2952 silver badges12 bronze badges
1
This is a JQuery plugin to change the button text of an input file element.
Example HTML:
<input type="file" id="choose-file" />
Example JS:
$('#choose-file').inputFileText({
text: 'Select File'
});
Result:
answered Jun 26, 2015 at 0:35
datchungdatchung
3,13624 silver badges24 bronze badges
1
<input id="uploadFile" placeholder="Choose File" disabled="disabled" />
<div class="fileUpload btn btn-primary">
<span>Your name</span>
<input id="uploadBtn" type="file" class="upload" />
</div>
JS
document.getElementById("uploadBtn").onchange = function () {
document.getElementById("uploadFile").value = this.value;
};
more http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/
Igor Ivancha
3,3854 gold badges31 silver badges39 bronze badges
answered Dec 11, 2014 at 10:49
webskywebsky
3,0221 gold badge34 silver badges31 bronze badges
0
Use <label>
for the caption
<form enctype='multipart/form-data' action='/uploads.php' method=post>
<label for=b1>
<u>Your</u> caption here
<input style='width:0px' type=file name=upfile id=b1
onchange='optionalExtraProcessing(b1.files[0])'
accept='image/png'>
</label>
</form>
This works without any javascript. You can decorate the label to any degree of complexity, to your heart’s content. When you click on the label, the click automatically gets redirected to the file input. The file input itself can be made invisible by any method. If you want the label to appear like a button, there are many solutions, e.g.:
label u {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: initial;
}
answered Sep 12, 2016 at 18:37
MKaamaMKaama
1,6242 gold badges18 silver badges26 bronze badges
I know, nobody asked for it but if anybody is using bootstrap, it can be changed through Label and CSS Pseudo-selector.
For changing button text:
.custom-file-label::after {
content: "What's up?";
}
For changing field text:
<label class="custom-file-label" for="upload">Drop it like it's hot</label>
Here’s a fiddle.
answered Jul 14, 2020 at 7:55
In Addition to MushyPeas answer, you can add a label to show the filename like so (no jQuery needed):
Credits also to this answer.
<input type="button" id="click-input" value="Write anything" onclick="document.getElementById('file').click();" />
<label for="click-input" id="file-name">Bla bla</label>
<input type="file" style="display:none;" id="file">
<script>
inputElement = document.getElementById('file')
labelElement = document.getElementById('file-name')
inputElement.onchange = function(event) {
var path = inputElement.value;
if (path) {
labelElement.innerHTML = path.split(/(\|/)/g).pop()
} else {
labelElement.innerHTML = 'Bla bla'
}
}
</script>
answered Sep 30, 2021 at 20:48
monty.pymonty.py
2,3791 gold badge15 silver badges28 bronze badges
Only CSS & bootstrap class
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="col-md-4 input-group">
<input class="form-control" type="text" />
<div class="input-group-btn">
<label for="files" class="btn btn-default">browse</label>
<input id="files" type="file" class="btn btn-default" style="visibility:hidden;" />
</div>
</div>
isherwood
56.5k16 gold badges109 silver badges151 bronze badges
answered Aug 8, 2018 at 8:58
EDIT: I see now by the comments that you are asking about the button text, and not the file path. My bad. I’ll leave my original answer below in case someone else who stumbles upon this question interprets it the way I originally did.
2nd EDIT: I had deleted this answer because I decided that I misunderstood the question and my answer was not relevant. However, comments in another answer indicated that people still wanted to see this answer so I’m undeleting it.
MY ORIGINAL ANSWER (I thought the OP was asking about the path, not the button text):
This is not a supported feature for security reasons. The Opera web browser used to support this but it was removed. Think about what would be possible if this were supported; You could make a page with a file upload input, pre-populate it with a path to some sensitive file and then auto-submit the form using javascript triggered by the onload
event. This would happen too fast for the user to do anything about it.
answered Dec 22, 2009 at 5:11
AsaphAsaph
157k25 gold badges193 silver badges197 bronze badges
In Bootstrap +4.5 you can simply add this to your code:
.custom-file-input~.custom-file-label::after {
content: "Your custom text ...";
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="custom-file">
<input type="file" class="custom-file-input">
<label class="custom-file-label">Your custom placeholder ...</label>
</div>
isherwood
56.5k16 gold badges109 silver badges151 bronze badges
answered Aug 27, 2020 at 23:01
What about icons without using real images and «interactivity»?
Check the following example that doesn’t use any image, not even javascript, and also it is interactive in the sense that changes its look on mouse events as on mouse-over and on mouse left or right click.
input
{
padding: 10px;
width: 100%;
}
input::file-selector-button
{
display: none;
}
input::before
{
border: 1px solid red;
border-radius: 3px 8px 3px 8px;
color: red;
content: attr(value)' Some more text';
margin: 25px;
padding: 5px;
}
input:hover:before
{
border: 1px groove blue;
background: lime;
}
input:active:before
{
border: 1px groove blue;
background: yellow;
}
<input type="file" value="📂 Open..." />
How it works:
Basically, it hides the main button of the standard file input element and shows its pseudo element, indicated by the :before part. Than it styles how it looks like and also some mouse events, so it is kind of «interactive».
Also using the :file-selector-button pseudo-element, allows to style the button it self or even to not display it at all as I have done int the above example with the code display: none;. This allows to use the :before element as replacement of the button.
The advantage of doing it with css is that by not using any javascript it will work even if the user’s browser has javascript disabled.
About the folder icon:
Actually it is a char it self in UNICODE: 📂 that is U+1F4C2 code-point. To see it correctly the user of the page must have a font that supports it. I did not install any new font into my system (Win7) and I see it correctly: so I suppose it is correctly seen by everyone else.
answered Sep 2, 2022 at 14:10
willy wonkawilly wonka
1,3201 gold badge17 silver badges29 bronze badges
Here is a way to «change» the text of an input with file type, with pure HTML and javascript:
<input id='browse' type='file' style='width:0px'>
<button id='browser' onclick='browse.click()'>
*The text you want*
</button>
Wai Ha Lee
8,41977 gold badges60 silver badges90 bronze badges
answered Apr 14, 2019 at 20:44
IntelarXIntelarX
1211 silver badge4 bronze badges
- Before that
<input type="file">
, add an image and<input style="position:absolute">
it will occupy the space of<input type="file">
-
Use the following CSS to the file element
position:relative; opacity:0; z-index:99;
Toby Speight
26.2k47 gold badges64 silver badges98 bronze badges
answered Jul 11, 2013 at 5:58
0
You can simply add some css trick. you don’t need javascript or more input files and i keep existing value attribute. you need to add only css. you can try this solution.
.btn-file-upload{
width: 187px;
position:relative;
}
.btn-file-upload:after{
content: attr(value);
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 48%;
background: #795548;
color: white;
border-radius: 2px;
text-align: center;
font-size: 12px;
line-height: 2;
}
<input type="file" class="btn-file-upload" value="Uploadfile" />
answered Mar 7, 2019 at 5:08
Udara KasunUdara Kasun
2,14316 silver badges25 bronze badges
for me it does not work the custom text with bootstrap-filestyle. It help with button decoration but text its weird to be changed, before get into wrestling with css i try the following :
$( document ).ready(function() {
$('.buttonText').html('Seleccione ficheros');
});
bootstrap-filestyle render the component as span with a class named butonText, so when document load just change the text. easy right and it must work on all browsers.
cheers
answered Apr 22, 2019 at 9:04
if you using rails and have problem apply it, I would like to add some tips from original answer posted by @Fernando Kosh
- Download file zip and copy file bootstrap-filestyle.min.js ke folder app/assets/javascripts/
-
open your application.js and add this line below
//= require bootstrap-filestyle.min
-
open your coffee and add this line
$(«:file»).filestyle({buttonName: «btn-primary»,buttonBefore: true,buttonText: » Your text here»,icon: false});
answered Mar 20, 2017 at 15:20
widjajaydwidjajayd
5,9423 gold badges29 silver badges39 bronze badges
I did it like this for my project:
.btn-outlined.btn-primary {
color: #000;
}
.btn-outlined.btn-primary:active, .btn-outlined.btn-positive:active, .btn-outlined.btn-negative:active {
color:#000;
}
.btn-block {
display: block;
width: 100%;
padding: 15px 0;
margin-bottom: 10px;
font-size: 18px;
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
<label for="fileUpload" class="btn btn-primary btn-block btn-outlined">Your text</label>
<input type="file" id="fileUpload"style="display: none;">
answered Apr 6, 2020 at 7:50
KhapiKhapi
5204 silver badges7 bronze badges
This is an alternative solution that may be of help to you. This hides the text that appears out of the button, mixing it with the background-color of the div. Then you can give the div a title you like.
<div style="padding:10px;font-weight:bolder; background-color:#446655;color: white;margin-top:10px;width:112px;overflow: hidden;">
UPLOAD IMAGE <input style="width:100px;color:#446655;display: inline;" type="file" />
</div>
Kaiido
116k11 gold badges201 silver badges258 bronze badges
answered Jun 15, 2013 at 4:49
2
<input type="file" value="Browse" name="avatar" id="id_avatar" />
I tried to modify the value
, but it’s not working. How to customize the button text?
BalusC
1.1m370 gold badges3586 silver badges3540 bronze badges
asked Dec 22, 2009 at 5:07
user198729user198729
60.6k107 gold badges250 silver badges346 bronze badges
4
Use Bootstrap FileStyle, which is used to style the file fields of forms. It is a plugin for a jQuery-based component library called Twitter Bootstrap
Sample usage:
Include:
<script type="text/javascript" src="js/bootstrap-filestyle.min.js"> </script>
Via JavaScript:
$(":file").filestyle();
Via data attributes:
<input type="file" class="filestyle" data-classButton="btn btn-primary" data-input="false" data-classIcon="icon-plus" data-buttonText="Your label here.">
answered Sep 20, 2013 at 4:57
Fernando KoshFernando Kosh
3,3321 gold badge35 silver badges30 bronze badges
8
Hide the file input. Create a new input to capture a click event and forward it to the hidden input:
<input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file"/>
2540625
10.7k8 gold badges49 silver badges56 bronze badges
answered Mar 27, 2016 at 13:58
11
You can put an image instead, and do it like this:
HTML:
<img src="/images/uploadButton.png" id="upfile1" style="cursor:pointer" />
<input type="file" id="file1" name="file1" style="display:none" />
JQuery:
$("#upfile1").click(function () {
$("#file1").trigger('click');
});
CAVEAT:
In IE9 and IE10 if you trigger the onClick in a file input via javascript, the form will be flagged as ‘dangerous’ and cannot be submitted with javascript, not sure if it can be submitted traditionally.
Charlie74
2,89714 silver badges23 bronze badges
answered Dec 29, 2011 at 11:58
ParParParPar
7,2277 gold badges43 silver badges54 bronze badges
6
The «upload file…» text is pre-defined by the browser and can’t be changed.
The only way to get around this is to use a Flash- or Java-based upload component like swfupload.
answered Dec 22, 2009 at 5:11
PekkaPekka
438k140 gold badges968 silver badges1083 bronze badges
3
Works Perfectly on All Browsers Hope it will work for you too.
HTML:
<input type="file" class="custom-file-input">
CSS:
.custom-file-input::-webkit-file-upload-button {
visibility: hidden;
}
.custom-file-input::before {
content: 'Select some files';
display: inline-block;
background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);
border: 1px solid #999;
border-radius: 3px;
padding: 5px 8px;
outline: none;
white-space: nowrap;
-webkit-user-select: none;
cursor: pointer;
text-shadow: 1px 1px #fff;
font-weight: 700;
font-size: 10pt;
}
.custom-file-input:hover::before {
border-color: black;
}
.custom-file-input:active::before {
background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);
}
Change content: 'Select some files';
with the text you want within ''
IF NOT WORKING WITH firefox then use this instead of input:
<label class="custom-file-input" for="Upload" >
</label>
<input id="Upload" type="file" multiple="multiple" name="_photos" accept="image/*" style="visibility: hidden">
answered Oct 3, 2015 at 6:32
Code BlackCode Black
5305 silver badges11 bronze badges
11
Simply
<label class="btn btn-primary">
<i class="fa fa-image"></i> Your text here<input type="file" style="display: none;" name="image">
</label>
[Edit with snippet]
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<label class="btn btn-primary">
<i class="fa fa-image"></i> Your text here<input type="file" style="display: none;" name="image">
</label>
answered Oct 31, 2018 at 4:59
Ken KarloKen Karlo
4664 silver badges5 bronze badges
1
I think this is what you want:
<button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>
<input type='file' id="getFile" style="display:none">
answered Dec 23, 2017 at 7:05
ChitChit
2952 silver badges12 bronze badges
1
This is a JQuery plugin to change the button text of an input file element.
Example HTML:
<input type="file" id="choose-file" />
Example JS:
$('#choose-file').inputFileText({
text: 'Select File'
});
Result:
answered Jun 26, 2015 at 0:35
datchungdatchung
3,13624 silver badges24 bronze badges
1
<input id="uploadFile" placeholder="Choose File" disabled="disabled" />
<div class="fileUpload btn btn-primary">
<span>Your name</span>
<input id="uploadBtn" type="file" class="upload" />
</div>
JS
document.getElementById("uploadBtn").onchange = function () {
document.getElementById("uploadFile").value = this.value;
};
more http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/
Igor Ivancha
3,3854 gold badges31 silver badges39 bronze badges
answered Dec 11, 2014 at 10:49
webskywebsky
3,0221 gold badge34 silver badges31 bronze badges
0
Use <label>
for the caption
<form enctype='multipart/form-data' action='/uploads.php' method=post>
<label for=b1>
<u>Your</u> caption here
<input style='width:0px' type=file name=upfile id=b1
onchange='optionalExtraProcessing(b1.files[0])'
accept='image/png'>
</label>
</form>
This works without any javascript. You can decorate the label to any degree of complexity, to your heart’s content. When you click on the label, the click automatically gets redirected to the file input. The file input itself can be made invisible by any method. If you want the label to appear like a button, there are many solutions, e.g.:
label u {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: initial;
}
answered Sep 12, 2016 at 18:37
MKaamaMKaama
1,6242 gold badges18 silver badges26 bronze badges
I know, nobody asked for it but if anybody is using bootstrap, it can be changed through Label and CSS Pseudo-selector.
For changing button text:
.custom-file-label::after {
content: "What's up?";
}
For changing field text:
<label class="custom-file-label" for="upload">Drop it like it's hot</label>
Here’s a fiddle.
answered Jul 14, 2020 at 7:55
In Addition to MushyPeas answer, you can add a label to show the filename like so (no jQuery needed):
Credits also to this answer.
<input type="button" id="click-input" value="Write anything" onclick="document.getElementById('file').click();" />
<label for="click-input" id="file-name">Bla bla</label>
<input type="file" style="display:none;" id="file">
<script>
inputElement = document.getElementById('file')
labelElement = document.getElementById('file-name')
inputElement.onchange = function(event) {
var path = inputElement.value;
if (path) {
labelElement.innerHTML = path.split(/(\|/)/g).pop()
} else {
labelElement.innerHTML = 'Bla bla'
}
}
</script>
answered Sep 30, 2021 at 20:48
monty.pymonty.py
2,3791 gold badge15 silver badges28 bronze badges
Only CSS & bootstrap class
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="col-md-4 input-group">
<input class="form-control" type="text" />
<div class="input-group-btn">
<label for="files" class="btn btn-default">browse</label>
<input id="files" type="file" class="btn btn-default" style="visibility:hidden;" />
</div>
</div>
isherwood
56.5k16 gold badges109 silver badges151 bronze badges
answered Aug 8, 2018 at 8:58
EDIT: I see now by the comments that you are asking about the button text, and not the file path. My bad. I’ll leave my original answer below in case someone else who stumbles upon this question interprets it the way I originally did.
2nd EDIT: I had deleted this answer because I decided that I misunderstood the question and my answer was not relevant. However, comments in another answer indicated that people still wanted to see this answer so I’m undeleting it.
MY ORIGINAL ANSWER (I thought the OP was asking about the path, not the button text):
This is not a supported feature for security reasons. The Opera web browser used to support this but it was removed. Think about what would be possible if this were supported; You could make a page with a file upload input, pre-populate it with a path to some sensitive file and then auto-submit the form using javascript triggered by the onload
event. This would happen too fast for the user to do anything about it.
answered Dec 22, 2009 at 5:11
AsaphAsaph
157k25 gold badges193 silver badges197 bronze badges
In Bootstrap +4.5 you can simply add this to your code:
.custom-file-input~.custom-file-label::after {
content: "Your custom text ...";
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="custom-file">
<input type="file" class="custom-file-input">
<label class="custom-file-label">Your custom placeholder ...</label>
</div>
isherwood
56.5k16 gold badges109 silver badges151 bronze badges
answered Aug 27, 2020 at 23:01
What about icons without using real images and «interactivity»?
Check the following example that doesn’t use any image, not even javascript, and also it is interactive in the sense that changes its look on mouse events as on mouse-over and on mouse left or right click.
input
{
padding: 10px;
width: 100%;
}
input::file-selector-button
{
display: none;
}
input::before
{
border: 1px solid red;
border-radius: 3px 8px 3px 8px;
color: red;
content: attr(value)' Some more text';
margin: 25px;
padding: 5px;
}
input:hover:before
{
border: 1px groove blue;
background: lime;
}
input:active:before
{
border: 1px groove blue;
background: yellow;
}
<input type="file" value="📂 Open..." />
How it works:
Basically, it hides the main button of the standard file input element and shows its pseudo element, indicated by the :before part. Than it styles how it looks like and also some mouse events, so it is kind of «interactive».
Also using the :file-selector-button pseudo-element, allows to style the button it self or even to not display it at all as I have done int the above example with the code display: none;. This allows to use the :before element as replacement of the button.
The advantage of doing it with css is that by not using any javascript it will work even if the user’s browser has javascript disabled.
About the folder icon:
Actually it is a char it self in UNICODE: 📂 that is U+1F4C2 code-point. To see it correctly the user of the page must have a font that supports it. I did not install any new font into my system (Win7) and I see it correctly: so I suppose it is correctly seen by everyone else.
answered Sep 2, 2022 at 14:10
willy wonkawilly wonka
1,3201 gold badge17 silver badges29 bronze badges
Here is a way to «change» the text of an input with file type, with pure HTML and javascript:
<input id='browse' type='file' style='width:0px'>
<button id='browser' onclick='browse.click()'>
*The text you want*
</button>
Wai Ha Lee
8,41977 gold badges60 silver badges90 bronze badges
answered Apr 14, 2019 at 20:44
IntelarXIntelarX
1211 silver badge4 bronze badges
- Before that
<input type="file">
, add an image and<input style="position:absolute">
it will occupy the space of<input type="file">
-
Use the following CSS to the file element
position:relative; opacity:0; z-index:99;
Toby Speight
26.2k47 gold badges64 silver badges98 bronze badges
answered Jul 11, 2013 at 5:58
0
You can simply add some css trick. you don’t need javascript or more input files and i keep existing value attribute. you need to add only css. you can try this solution.
.btn-file-upload{
width: 187px;
position:relative;
}
.btn-file-upload:after{
content: attr(value);
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 48%;
background: #795548;
color: white;
border-radius: 2px;
text-align: center;
font-size: 12px;
line-height: 2;
}
<input type="file" class="btn-file-upload" value="Uploadfile" />
answered Mar 7, 2019 at 5:08
Udara KasunUdara Kasun
2,14316 silver badges25 bronze badges
for me it does not work the custom text with bootstrap-filestyle. It help with button decoration but text its weird to be changed, before get into wrestling with css i try the following :
$( document ).ready(function() {
$('.buttonText').html('Seleccione ficheros');
});
bootstrap-filestyle render the component as span with a class named butonText, so when document load just change the text. easy right and it must work on all browsers.
cheers
answered Apr 22, 2019 at 9:04
if you using rails and have problem apply it, I would like to add some tips from original answer posted by @Fernando Kosh
- Download file zip and copy file bootstrap-filestyle.min.js ke folder app/assets/javascripts/
-
open your application.js and add this line below
//= require bootstrap-filestyle.min
-
open your coffee and add this line
$(«:file»).filestyle({buttonName: «btn-primary»,buttonBefore: true,buttonText: » Your text here»,icon: false});
answered Mar 20, 2017 at 15:20
widjajaydwidjajayd
5,9423 gold badges29 silver badges39 bronze badges
I did it like this for my project:
.btn-outlined.btn-primary {
color: #000;
}
.btn-outlined.btn-primary:active, .btn-outlined.btn-positive:active, .btn-outlined.btn-negative:active {
color:#000;
}
.btn-block {
display: block;
width: 100%;
padding: 15px 0;
margin-bottom: 10px;
font-size: 18px;
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
<label for="fileUpload" class="btn btn-primary btn-block btn-outlined">Your text</label>
<input type="file" id="fileUpload"style="display: none;">
answered Apr 6, 2020 at 7:50
KhapiKhapi
5204 silver badges7 bronze badges
This is an alternative solution that may be of help to you. This hides the text that appears out of the button, mixing it with the background-color of the div. Then you can give the div a title you like.
<div style="padding:10px;font-weight:bolder; background-color:#446655;color: white;margin-top:10px;width:112px;overflow: hidden;">
UPLOAD IMAGE <input style="width:100px;color:#446655;display: inline;" type="file" />
</div>
Kaiido
116k11 gold badges201 silver badges258 bronze badges
answered Jun 15, 2013 at 4:49
2
Примеры изменения вида стандартного поля для загрузки файлов (input[type=file]
) с помощью CSS и JS.
1
Стандартный вид
- HTML
- CSS
- JS/JQuery
<form method="post" enctype="multipart/form-data">
<label class="input-file">
<input type="file" name="file">
<span class="input-file-btn">Выберите файл</span>
<span class="input-file-text">Максимум 10мб</span>
</label>
</form>
HTML
.input-file {
position: relative;
display: inline-block;
}
.input-file-btn {
position: relative;
display: inline-block;
cursor: pointer;
outline: none;
text-decoration: none;
font-size: 14px;
vertical-align: middle;
color: rgb(255 255 255);
text-align: center;
border-radius: 4px;
background-color: #419152;
line-height: 22px;
height: 40px;
padding: 10px 20px;
box-sizing: border-box;
border: none;
margin: 0;
transition: background-color 0.2s;
}
.input-file-text {
padding: 0 10px;
line-height: 40px;
display: inline-block;
}
.input-file input[type=file] {
position: absolute;
z-index: -1;
opacity: 0;
display: block;
width: 0;
height: 0;
}
/* Focus */
.input-file input[type=file]:focus + .input-file-btn {
box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}
/* Hover/active */
.input-file:hover .input-file-btn {
background-color: #59be6e;
}
.input-file:active .input-file-btn {
background-color: #2E703A;
}
/* Disabled */
.input-file input[type=file]:disabled + .input-file-btn {
background-color: #eee;
}
CSS
$('.input-file input[type=file]').on('change', function(){
let file = this.files[0];
$(this).closest('.input-file').find('.input-file-text').html(file.name);
});
JS
Результат:
2
Обычная кнопка
- HTML
- CSS
- JS/JQuery
<form method="post" enctype="multipart/form-data">
<label class="input-file">
<input type="file" name="file">
<span>Выберите файл</span>
</label>
</form>
HTML
.input-file {
position: relative;
display: inline-block;
}
.input-file span {
position: relative;
display: inline-block;
cursor: pointer;
outline: none;
text-decoration: none;
font-size: 14px;
vertical-align: middle;
color: rgb(255 255 255);
text-align: center;
border-radius: 4px;
background-color: #419152;
line-height: 22px;
height: 40px;
padding: 10px 20px;
box-sizing: border-box;
border: none;
margin: 0;
transition: background-color 0.2s;
}
.input-file input[type=file] {
position: absolute;
z-index: -1;
opacity: 0;
display: block;
width: 0;
height: 0;
}
/* Focus */
.input-file input[type=file]:focus + span {
box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}
/* Hover/active */
.input-file:hover span {
background-color: #59be6e;
}
.input-file:active span {
background-color: #2E703A;
}
/* Disabled */
.input-file input[type=file]:disabled + span {
background-color: #eee;
}
CSS
$('.input-file input[type=file]').on('change', function(){
let file = this.files[0];
$(this).next().html(file.name);
});
JS
Результат:
3
В виде input text
- HTML
- CSS
- JS/JQuery
<form method="post" enctype="multipart/form-data">
<label class="input-file">
<span class="input-file-text" type="text"></span>
<input type="file" name="file">
<span class="input-file-btn">Выберите файл</span>
</label>
</form>
HTML
.input-file {
position: relative;
display: inline-block;
}
.input-file-text {
padding: 0 10px;
line-height: 40px;
text-align: left;
height: 40px;
display: block;
float: left;
box-sizing: border-box;
width: 200px;
border-radius: 6px 0px 0 6px;
border: 1px solid #ddd;
}
.input-file-btn {
position: relative;
display: inline-block;
cursor: pointer;
outline: none;
text-decoration: none;
font-size: 14px;
vertical-align: middle;
color: rgb(255 255 255);
text-align: center;
border-radius: 0 4px 4px 0;
background-color: #419152;
line-height: 22px;
height: 40px;
padding: 10px 20px;
box-sizing: border-box;
border: none;
margin: 0;
transition: background-color 0.2s;
}
.input-file input[type=file] {
position: absolute;
z-index: -1;
opacity: 0;
display: block;
width: 0;
height: 0;
}
/* Focus */
.input-file input[type=file]:focus + .input-file-btn {
box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}
/* Hover/active */
.input-file:hover .input-file-btn {
background-color: #59be6e;
}
.input-file:active .input-file-btn {
background-color: #2E703A;
}
/* Disabled */
.input-file input[type=file]:disabled + .input-file-btn {
background-color: #eee;
}
CSS
$('.input-file input[type=file]').on('change', function(){
let file = this.files[0];
$(this).closest('.input-file').find('.input-file-text').html(file.name);
});
JS
Результат:
4
Input file со списком выбранных файлов
- HTML
- CSS
- JS/JQuery
<form method="post" enctype="multipart/form-data">
<div class="input-file-row">
<label class="input-file">
<input type="file" name="file[]" multiple>
<span>Выберите файл</span>
</label>
<div class="input-file-list"></div>
</div>
</form>
HTML
.input-file-row {
display: inline-block;
}
.input-file {
position: relative;
display: inline-block;
}
.input-file span {
position: relative;
display: inline-block;
cursor: pointer;
outline: none;
text-decoration: none;
font-size: 14px;
vertical-align: middle;
color: rgb(255 255 255);
text-align: center;
border-radius: 4px;
background-color: #419152;
line-height: 22px;
height: 40px;
padding: 10px 20px;
box-sizing: border-box;
border: none;
margin: 0;
transition: background-color 0.2s;
}
.input-file input[type=file] {
position: absolute;
z-index: -1;
opacity: 0;
display: block;
width: 0;
height: 0;
}
/* Focus */
.input-file input[type=file]:focus + span {
box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}
/* Hover/Active */
.input-file:hover span {
background-color: #59be6e;
}
.input-file:active span {
background-color: #2E703A;
}
/* Disabled */
.input-file input[type=file]:disabled + span {
background-color: #eee;
}
/* Список файлов */
.input-file-list {
padding: 10px 0;
}
.input-file-list-item {
margin-bottom: 10px;
}
.input-file-list-remove {
color: red;
text-decoration: none;
display: inline-block;
margin-left: 5px;
}
CSS
var dt = new DataTransfer();
$('.input-file input[type=file]').on('change', function(){
let $files_list = $(this).closest('.input-file').next();
$files_list.empty();
for(var i = 0; i < this.files.length; i++){
let new_file_input = '<div class="input-file-list-item">' +
'<span class="input-file-list-name">' + this.files.item(i).name + '</span>' +
'<a href="#" onclick="removeFilesItem(this); return false;" class="input-file-list-remove">x</a>' +
'</div>';
$files_list.append(new_file_input);
dt.items.add(this.files.item(i));
};
this.files = dt.files;
});
function removeFilesItem(target){
let name = $(target).prev().text();
let input = $(target).closest('.input-file-row').find('input[type=file]');
$(target).closest('.input-file-list-item').remove();
for(let i = 0; i < dt.items.length; i++){
if(name === dt.items[i].getAsFile().name){
dt.items.remove(i);
}
}
input[0].files = dt.files;
}
JS
Результат:
5
Загрузка изображений с превью
- HTML
- CSS
- JS/JQuery
<form method="post" enctype="multipart/form-data">
<div class="input-file-row">
<label class="input-file">
<input type="file" name="file[]" multiple accept="image/*">
<span>Выберите файл</span>
</label>
<div class="input-file-list"></div>
</div>
</form>
HTML
.input-file-row {
display: inline-block;
}
.input-file {
position: relative;
display: inline-block;
}
.input-file span {
position: relative;
display: inline-block;
cursor: pointer;
outline: none;
text-decoration: none;
font-size: 14px;
vertical-align: middle;
color: rgb(255 255 255);
text-align: center;
border-radius: 4px;
background-color: #419152;
line-height: 22px;
height: 40px;
padding: 10px 20px;
box-sizing: border-box;
border: none;
margin: 0;
transition: background-color 0.2s;
}
.input-file input[type=file] {
position: absolute;
z-index: -1;
opacity: 0;
display: block;
width: 0;
height: 0;
}
/* Focus */
.input-file input[type=file]:focus + span {
box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}
/* Hover/active */
.input-file:hover span {
background-color: #59be6e;
}
.input-file:active span {
background-color: #2E703A;
}
/* Disabled */
.input-file input[type=file]:disabled + span {
background-color: #eee;
}
/* Список c превью */
.input-file-list {
padding: 10px 0;
}
.input-file-list-item {
display: inline-block;
margin: 0 15px 15px;
width: 150px;
vertical-align: top;
position: relative;
}
.input-file-list-item img {
width: 150px;
}
.input-file-list-name {
text-align: center;
display: block;
font-size: 12px;
text-overflow: ellipsis;
overflow: hidden;
}
.input-file-list-remove {
color: #fff;
text-decoration: none;
display: inline-block;
position: absolute;
padding: 0;
margin: 0;
top: 5px;
right: 5px;
background: #ff0202;
width: 16px;
height: 16px;
text-align: center;
line-height: 16px;
border-radius: 50%;
}
CSS
var dt = new DataTransfer();
$('.input-file input[type=file]').on('change', function(){
let $files_list = $(this).closest('.input-file').next();
$files_list.empty();
for(var i = 0; i < this.files.length; i++){
let file = this.files.item(i);
dt.items.add(file);
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function(){
let new_file_input = '<div class="input-file-list-item">' +
'<img class="input-file-list-img" src="' + reader.result + '">' +
'<span class="input-file-list-name">' + file.name + '</span>' +
'<a href="#" onclick="removeFilesItem(this); return false;" class="input-file-list-remove">x</a>' +
'</div>';
$files_list.append(new_file_input);
}
};
this.files = dt.files;
});
function removeFilesItem(target){
let name = $(target).prev().text();
let input = $(target).closest('.input-file-row').find('input[type=file]');
$(target).closest('.input-file-list-item').remove();
for(let i = 0; i < dt.items.length; i++){
if(name === dt.items[i].getAsFile().name){
dt.items.remove(i);
}
}
input[0].files = dt.files;
}
JS
Результат:
Не смотря на развитие, внедрение новых стандартов и плюшек в браузерах, у нет единых стандартов, как отображать элемент /> по умолчанию. Более того, у этого элемента нет атрибутов, позволяющих его в какой-то мере стилизовать.
Из-за необходимости привести это поле формы к единому виду во всех браузерах и «вписать» в разработанный дизайн, после поисков и анализа материалов в интернете был разработан метод замены вида поля формы на html+css, и js для расширения функциональности.
Как по умолчанию выглядит это поле?
<input id="upload" type="file" name="upload" />
Так он выглядит в Internet Explorer 9:
А так — в Firefox:
В Google Chrome:
В Opera:
В Safari:
Стилизация поля file
В то место, где должно быть поле выбора файла, вставим следующий код:
<div class="fileform">
<div class="selectbutton">Обзор</div>
<input id="upload" type="file" name="upload" />
</div>
В файл стилей добавим такие блоки:
.fileform {
background-color: #FFFFFF;
border: 1px solid #CCCCCC;
border-radius: 2px;
cursor: pointer;
height: 26px;
overflow: hidden;
padding: 2px;
position: relative;
text-align: left;
vertical-align: middle;
width: 230px;
}
.fileform .selectbutton {
background-color: #A2A3A3;
border: 1px solid #939494;
border-radius: 2px;
color: #FFFFFF;
float: right;
font-size: 16px;
height: 20px;
line-height: 20px;
overflow: hidden;
padding: 2px 6px;
text-align: center;
vertical-align: middle;
width: 50px;
}
.fileform #upload{
position:absolute;
top:0;
left:0;
width:100%;
-moz-opacity: 0;
filter: alpha(opacity=0);
opacity: 0;
font-size: 150px;
height: 30px;
z-index:20;
}
Теперь во всех браузерах поле формы выглядит одинаково, при этом форма выбора файла всё так же появляется по клику и на поле и на кнопку:
Главный недостаток полученного решения от стандартной формы — оно никак визуально не сигнализирует о том, что файл был выбран. Эта проблема решается с использованием javascript.
Добавление подписи о выбранном файле
Добавим к полю функцию-обработчик событий, а к блоку — еще один блок-заголовок и, конечно, его стиль:
<div class="fileform">
<div id="fileformlabel"></div>
<div class="selectbutton">Обзор</div>
<input type="file" name="upload" id="upload" onchange="getName(this.value);" />
</div>
.fileform #fileformlabel {
background-color: #FFFFFF;
float: left;
height: 22px;
line-height: 22px;
overflow: hidden;
padding: 2px;
text-align: left;
vertical-align: middle;
width:160px;
}
Сама функция-обработчик получает полное имя выбранного файла, отбрасывает путь (с проверкойдля разных файловых систем), сохраняет имя с расширением в переменную filename и записывает его в блок fileformlabel.
function getName (str){
if (str.lastIndexOf('\')){
var i = str.lastIndexOf('\')+1;
}
else{
var i = str.lastIndexOf('/')+1;
}
var filename = str.slice(i);
var uploaded = document.getElementById("fileformlabel");
uploaded.innerHTML = filename;
}
Теперь поле формы выглядит так (при этом можно менять его размер, цвет, шрифт и выравнивание):
Данная заметка — реализация метода, предложенного в статье «Кастомизация input type=”file” с помощью CSS»
User281315223 posted
Sadly, the File <input> element is one of those common elements for which there is no «easy» method for changing the style, text or appearance of (significantly) as it is pre-defined by the browser. With that being said, there are
still a few different ways of getting around this through CSS, Javascript and a few other options.
Using an Image to Replace your File Input
There are several workarounds for handling some thing like this, which involves using an image or other element to overlay the area that would be your File Upload element through CSS and using Javascript to handle when the button click occurs.
I would recommend the following tutorials which provides a common step-by-step approaches for handling this :
- Styling a File Input
- Styling File Inputs through CSS and Javascript
- File Styling Plugin through jQuery
and an actual implementation might look something like this as mentioned in this
related Stack Overflow discussion :
<!-- Markup --> <img src="/Images/Upload.jpg" id="upfile1" style="cursor:pointer" /> <input type="file" id="file1" name="file1" style="display:none" /> <!-- Related jQuery code --> <script type='text/javascript'> $(function(){ //Maps your button click event to the File Upload click event $("#upfile1").click(function () { $("#file1").trigger('click'); }); }); </script>
Additionally, you could simply hide the element using jQuery as well and style it as you choose :
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type='text/javascript'> $(function(){ // Wrap your File input in a wrapper <div> var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'}); var fileInput = $(':file').wrap(wrapper); // When your file input changes, update the text for your button fileInput.change(function(){ $this = $(this); // If the selection is empty, reset it if($this.val().length == 0) { $('#file').text("Your Text to Choose a File Here!"); }else{ $('#file').text($this.val()); } }) // When your fake button is clicked, simulate a click of the file button $('#file').click(function(){ fileInput.click(); }).show(); }); </script> </head> <body> <!-- Define your button --> <button id="file">Your Text to Choose a File Here!</button> <!-- Your File element --> <input type="file" name="file" /> </body> </html>
- Working Example
Using a File-Based Flash, Silverlight or Other Plugin
Since styling these elements can prove to be difficult, a common approach is to use a third-party tool such as Flash or Silverlight to handle your uploading mechanism, which can permit for more freedom in terms of styling and appearance.
Some of the common choices for handling this are :
- SWFUpload
- Uploadify
- PLUpload
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
There are quite a few techniques for “customizing” the <input type="file" />
element. I tried most of them, but none was good enough to have on Readerrr (for importing feeds by uploading a file). Probably the worst technique was the one where the input element is put into a container (which imitates a button), and the input follows the cursor so that when you click anywhere on the container, you actually click the input. Sounds interesting and weird at the same time, right? Anyway, it had some unacceptable drawbacks (usability, touch).
As as result, I tried googling for an unseen solution. Once it seemed that there was nothing new, my I eyes were caught by a comment on StackOverflow. It had just a few up votes and was lost somewhere in the middle of the page, but most importantly it contained a magic word – <label>
! As you may know, pressing a label basically triggers the focus event for the bound input. Interesting thing is that, if it is a file input, it works out as a click event, resulting in opening a file browser. This is great for crafting a semantic solution.
<input type="file" name="file" id="file" class="inputfile" /> <label for="file">Choose a file</label>
So, pressing any of these two elements gives us the same result. That means that the most difficult part is… solved! No JavaScript, no other complex solutions like cursor position tracking, just these two lines. See for yourself:
Now let’s just style it and make this look like a normal button.
Hiding the <input>
First off, we need to hide the ugly duckling. CSS properties such as display: none
or visibility: hidden
will not work out. The reasons are: the input value will not be sent to the server on form submit; the input will be excluded out of tab order (you want your website to be accessible, right?). I set up a combination of CSS properties/values for hiding the input visually but keeping it visible for the browser:
.inputfile { width: 0.1px; height: 0.1px; opacity: 0; overflow: hidden; position: absolute; z-index: -1; }
I see you are wondering why width
and height
are set to 0.1px
instead of just 0px
. Setting the property values to zero ends up throwing the element out of tab party in some browsers. And position: absolute
guarantees the element does not interfere with the sibling elements.
Styling the <label>
Since the <label>
element is visually the button, you can use all of your creative CSS juices on it. I’m sticking to something very simple for now:
.inputfile + label { font-size: 1.25em; font-weight: 700; color: white; background-color: black; display: inline-block; } .inputfile:focus + label, .inputfile + label:hover { background-color: red; }
Accessibility
How do you know that an element on the website is pressable? Firstly, the element should communicate a feeling that you can tap or click on it. Secondly, the cursor icon should change to an appropriate one when hovering the element. The former we’ve solved previously, let’s solve the latter, because labels do not trigger a cursor change by default:
.inputfile + label { cursor: pointer; /* "hand" cursor */ }
Keyboard Navigation
If users are unable to navigate on your website using just a keyboard, you are doing something wrong. Hiding the input itself in a correct manner was one thing, the other is indicating when the element is focused, i.e. rendering .inputfile:focus
on the label
:
.inputfile:focus + label { outline: 1px dotted #000; outline: -webkit-focus-ring-color auto 5px; }
-webkit-focus-ring-color auto 5px
is a little trick for obtaining default outline looks on Chrome, Opera and Safari. The style in the line above is for browsers that do not understand the -webkit…
expression.
Possible Touch Issues
In case you’ve been using FastClick (a library for eliminating the 300ms tap-pause on touch-capable devices) and have plans to add some extra markup to the content of a label, the button won’t work as it should, unless you use pointer-events: none
, respectively:
<label for="file"><strong>Choose a file</strong></label>
.inputfile + label * { pointer-events: none; }
JavaScript Enhancement
Probably and hopefully the last thing missing is indicating if files were selected. The file input does usually indicate that, but in our case the input is visually hidden. Luckily, there is a way out: a tiny JavaScript enhancement. The text of a label becomes the name of the selected file. If there were multiple files selected, the text will tell us how many of them were selected.
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple />
var inputs = document.querySelectorAll( '.inputfile' ); Array.prototype.forEach.call( inputs, function( input ) { var label = input.nextElementSibling, labelVal = label.innerHTML; input.addEventListener( 'change', function( e ) { var fileName = ''; if( this.files && this.files.length > 1 ) fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length ); else fileName = e.target.value.split( '' ).pop(); if( fileName ) label.querySelector( 'span' ).innerHTML = fileName; else label.innerHTML = labelVal; }); });
There is also a jQuery version of this code presented in the source of the demo files. Make sure to check them out.
A little explanation:
- Having the native
[multiple]
attribute allows users to select more than one file per upload. Whereas[data-multiple-caption]
is a fictive attribute for expressing the message if multiple files were selected. Here you can set a custom message. The use of the{count}
phrase is optional and the fragment is replaced with the number of files selected. The reason I use an additional HTML attribute instead of assigning this sentence as a value for a JavaScript variable is because it’s much easier to maintain the copy when it is in one place. - HTML attribute
[multiple]
is not supported in IE 9 and below and neither is thefiles
property of JavaScript. For the latter case, we simply rely onvalue
. Since it usually has a value ofC:fakepathfilename.jpg
format, thesplit( '' ).pop()
extracts what’s actual – the name of the file. - An interesting thing is that you can unset a value of the input by pressing the ESC button while in the file browser. This is possible only in Chrome and Opera. Therefore, we use
labelVal
for storing the default value of the label and bringing it back when necessary.
This is how the final result looks like:
What if JavaScript is not available?
Since there is no JavaScript-less way to indicate if any files were selected, it would be better to rely on the default looks of the file input for the sake of usability. All we need to do is to add a .no-js
class name to the <html>
element and then use JavaScript and replace it with .js
– that’s how we will know if JavaScript is available.
<html class="no-js"> <head> <!-- remove this if you use Modernizr --> <script>(function(e,t,n){var r=e.querySelectorAll("html")[0];r.className=r.className.replace(/(^|s)no-js(s|$)/,"$1js$2")})(document,window,0);</script> </head> </html>
The CSS part accordingly:
.js .inputfile { width: 0.1px; height: 0.1px; opacity: 0; overflow: hidden; position: absolute; z-index: -1; } .no-js .inputfile + label { display: none; }
Firefox Bug
It is quite unexpected that Firefox completely ignores the input[type="file"]:focus
expression, whereas :hover
and :active
work just fine! Surprisingly, Firefox allows to catch the focus
event in JavaScript, so the workaround is adding a class to the file input element that let’s us control the focus style:
input.addEventListener( 'focus', function(){ input.classList.add( 'has-focus' ); }); input.addEventListener( 'blur', function(){ input.classList.remove( 'has-focus' ); });
.inputfile:focus + label, .inputfile.has-focus + label { outline: 1px dotted #000; outline: -webkit-focus-ring-color auto 5px; }
Check out the example styles in the demo to see how to style the file input element according to your needs. Make sure to take a look at the source code of the demo and feel free to use this technique in your projects. Happy uploading!
The icon in the demo is made by Daniel Bruce from www.flaticon.com and it is licensed under CC BY 3.0.