ChatGPT解决这个技术问题 Extra ChatGPT

Change default text in input type="file"?

I want to change default text on button that is "Choose File" when we use input="file".

https://i.stack.imgur.com/rcdgH.png

How can I do this? Also as you can see in image button is on left side of text. How can I put it on right side of text?

There is option to get this text to variable?
Answer by ParPar over here is probably what you are looking for: stackoverflow.com/questions/1944267/… .
possible duplicate of How to rename HTML "browse" button of an input type=file? for the text part, for style in general: stackoverflow.com/questions/572768/…

W
Whymarrh

Use the for attribute of label for input.

<div>
  <label for="files" class="btn">Select Image</label>
  <input id="files" style="visibility:hidden;" type="file">
</div>

Below is the code to fetch name of the uploaded file

$("#files").change(function() { filename = this.files[0].name; console.log(filename); });


display:none can be used on INPUT so it won't use not needed space.
Thank you. This worked perfectly, and was exactly what I was looking for.
Works fine on Mac with Chrome, FF and Safari. If it does it also on IE then this is the best and simplest option to style the file input button. Thanks!
works well, only slight negative is that the user can't see the name of the file that has been selected upon selection.
@Mike Updated the post to fetch filename
C
Community

I think this is what you want:

JS Bin


best solution here so far.
This also handles keyboard navigation. To make it perfect, use tabindex="-1" on the hidden file input to skip it while tabbing.
S
SFin

Each browser has it's own rendition of the control and as such you can't change either the text or the orientation of the control.

There are some "kind of" hacks you may want to try if you want an / solution rather than a Flash or solution.

http://www.quirksmode.org/dom/inputfile.html

http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom

Personally, because most users stick to their browser of choice, and therefore are probably used to seeing the control in the default rendition, they'd probably get confused if they saw something different (depending on the types of users you're dealing with).


P
Paulo Mogollón

This might help someone in the future, you can style the label for the input as you like and put anything you want inside it and hide the input with display none.

It works perfectly on cordova with iOS


A
Anuraj

It is not possible. Otherwise you may need to use Silverlight or Flash upload control.


Which is not possible? Changing text or placing button on right or both?
I upvoted this, because I think it's unfair to downvote this answer. It's basically impossible to change the text of the native file input button. The "possible solutions" are all hacks or workarounds.
@PeterLee - Hacks are solutions, some even follows the W3C spec.
G
Gass

To achieve this, the default input button must be hidden using display:none CSS property and a new button element is added to replace it, so we can customize as we wish.

With Bootstrap

Optional text here

With jQuery

In this case the onclick attribute added to the button element is indicating to JavaScript to click on the hidden default input button whenever the visible button is clicked.

Optional text here

Plain JavaScript with event listener

document.getElementById('btn').addEventListener('click', () => { document.getElementById('input').click(); }) Optional text here


R
Rokive

$(document).ready(function () { $('#choose-file').change(function () { var i = $(this).prev('label').clone(); var file = $('#choose-file')[0].files[0].name; $(this).prev('label').text(file); }); }); .custom-file-upload{ background: #f7f7f7; padding: 8px; border: 1px solid #e3e3e3; border-radius: 5px; border: 1px solid #ccc; display: inline-block; padding: 6px 12px; cursor: pointer; } can you try this


T
Tushar Shukla

The trick is to trigger a click event on click of the file input and manage the visibility of the default input file via CSS. Here's how you can do it: jQuery:

$(function() {
  $("#labelfile").click(function() {
    $("#imageupl").trigger('click');
  });
})

css

.file {
  position: absolute;
  clip: rect(0px, 0px, 0px, 0px);
  display: block;
}

.labelfile {
  color: #333;
  background-color: #fff;
  display: inline-block;
  margin-bottom: 0;
  font-weight: 400;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  background-image: none;
  white-space: nowrap;
  padding: 6px 8px;
  font-size: 14px;
  line-height: 1.42857143;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

HTML code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <input name="imageupl" type="file" id="imageupl" class="file" />
  <label class="labelfile" id="labelfile"><i class="icon-download-alt"></i> Browse File</label>
</div>

T
Thielicious

I made a script and published it at GitHub: get selectFile.js Easy to use, feel free to clone.

HTML

<input type=file hidden id=choose name=choose>
<input type=button onClick=getFile.simulate() value=getFile>
<label id=selected>Nothing selected</label>

JS

var getFile = new selectFile;
getFile.targets('choose','selected');

DEMO

jsfiddle.net/Thielicious/4oxmsy49/


u
user3784950

Update 2017:

I have done research on how this could be achieved. And the best explanation/tutorial is here: https://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/

I'll write summary here just in case it becomes unavailable. So you should have HTML:

<input type="file" name="file" id="file" class="inputfile" />
<label for="file">Choose a file</label>

Then hide the input with CSS:

.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;}

Then style the label:

.inputfile + label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: black;
display: inline-block;
}

Then optionally you can add JS to display the name of the file:

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;
});
});

But really just read the tutorial and download the demo, it's really good.


J
Jared Forth

This should work:

input.*className*::-webkit-file-upload-button {
  *style content..*
}

L
Leon Tanko

Here is how its done with bootstrap, only u should put the original input somewhere...idk in head and delete the < br > if you have it, because its only hidden and its taking space anyway :)


T
Tushar Shukla

Using Bootstrap you can do this thing like the below code.

<!DOCTYPE html>
<html lang="en">
<head>

  <style>
    .btn-file {
      position: relative;
      overflow: hidden;
    }

    .btn-file input[type=file] {
      position: absolute;
      top: 0;
      right: 0;
      min-width: 100%;
      min-height: 100%;
      font-size: 100px;
      text-align: right;
      filter: alpha(opacity=0);
      opacity: 0;
      outline: none;
      background: white;
      cursor: inherit;
      display: block;
    }

  </style>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <span class="btn btn-file">Upload image from here<input type="file">
</body>
</html>

This code does not print back to the web page what file was chosen.
S
Sony Santos

I'd use a button to trigger the input:

<button onclick="document.getElementById('fileUpload').click()">Open from File...</button>
<input type="file" id="fileUpload" name="files" style="display:none" />

Quick and clean.


И
Илья Зеленько

You can use this approach, it works even if a lot of files inputs.

const fileBlocks = document.querySelectorAll('.file-block') const buttons = document.querySelectorAll('.btn-select-file') ;[...buttons].forEach(function (btn) { btn.onclick = function () { btn.parentElement.querySelector('input[type="file"]').click() } }) ;[...fileBlocks].forEach(function (block) { block.querySelector('input[type="file"]').onchange = function () { const filename = this.files[0].name block.querySelector('.btn-select-file').textContent = 'File selected: ' + filename } }) .btn-select-file { border-radius: 20px; } input[type="file"] { display: none; }



I like this approach, but for me Selected File text not showing up, any idea what is the issue. I am google chrome
b
bagatov88

My solution...

HTML :

<input type="file" id="uploadImages" style="display:none;" multiple>

<input type="button" id="callUploadImages" value="Select">
<input type="button" id="uploadImagesInfo" value="0 file(s)." disabled>
<input type="button" id="uploadProductImages" value="Upload">

Jquery:

$('#callUploadImages').click(function(){

    $('#uploadImages').click();
});

$('#uploadImages').change(function(){

    var uploadImages = $(this);
    $('#uploadImagesInfo').val(uploadImages[0].files.length+" file(s).");
});

This is just evil :D


J
Jadin Hornsby

Ok so very simple pure css way of creating your custom input file.

Use labels, but as you know from previous answers, label doesn't invoke onclick function in firefox, may be a bug but doesn't matter with the following.

<label for="file"  class="custom-file-input"><input type="file"  name="file" class="custom-file-input"></input></label>

What you do is style the label to look how you want it to

    .custom-file-input {
        color: transparent;/* This is to take away the browser text for file uploading*/
        /* Carry on with the style you want */
        background: url(../img/doc-o.png);
        background-size: 100%;
        position: absolute;
        width: 200px;
        height: 200px;
        cursor: pointer;
        top: 10%;
        right: 15%;
    }

now simply hide the actual input button, but you cant set it to to visability: hidden

So make in invisible by setting opacity: 0;

input.custom-file-input {
    opacity: 0;
    position: absolute;/*set position to be exactly over your input*/
    left: 0;
    top: 0;
}

now as you might have noticed i have the same class on my label as i do my input field, that is because i want the to both have the same styling, thus where ever you click on the label, you are actually clicking on the invisible input field.


C
Carson

I build a script that can be easier to do that.

For example:

basically, my script is very similar to this link

Code

Pure javascript, no dependencies needed

Reference

What is the difference between visibility:hidden and display:none?

data-*


h
hostingutilities.com

Below is an example of a stylized upload button that will read an image, compress it, and download the resulting image. It works by hiding the actual input element, and then through some trickery we make it so that when you click on our fake file uploader it uses the actual input element to pop up the window for choosing a file. By using this method we get 100% control over how the file uploader looks since we are using our own element instead of styling the file upload menu. It also makes it easy to add drag and drop functionality in the future if we ever want to do that.

And then I actually created a series of blog posts about this file upload button.

'use strict' var AMOUNT = 10 var WIDTH = 600 var HEIGHT = 400 var canvas = document.getElementById('canvas') canvas.width = WIDTH canvas.height = HEIGHT //here's how I created the clickable area //user clicks the clickable area > we send a click event //to the file opener > the file opener clicks on the open //file button > the open file dialogue pops up function clickableAreaListener(e){ let clickEvent = new CustomEvent("click",{"from":"fileOpenerHandler"}); document.getElementById("fileOpener").dispatchEvent(clickEvent); } function fileOpenerListener(e) { document.getElementById("file-btn").click(); e.preventDefault(); } function fileSelectedListener(e){ readFiles(e.target.files); } document.getElementById('file-btn').addEventListener('change', fileSelectedListener); document.getElementById("clickable-area").addEventListener('click', clickableAreaListener); document.getElementById("fileOpener").addEventListener("click", fileOpenerListener); function readFiles(files){ files = [].slice.call(files); //turning files into a normal array for (var file of files){ var reader = new FileReader(); reader.onload = createOnLoadHandler(file); reader.onerror = fileErrorHandler; //there are also reader.onloadstart, reader.onprogress, and reader.onloadend handlers reader.readAsDataURL(file); } } function fileErrorHandler(e) { switch(e.target.error.code) { case e.target.error.NOT_FOUND_ERR: throw 'Image not found'; break; case e.target.error.NOT_READABLE_ERR: throw 'Image is not readable'; break; case e.target.error.ABORT_ERR: break; default: throw 'An error occurred while reading the Image'; }; } function createOnLoadHandler(file){ console.log('reading ' + file.name + ' of type ' + file.type) //file.type will be either image/jpeg or image/png function onLoad(e){ var data = e.target.result display(data); var compressedData = compressCanvas(AMOUNT) download(compressedData) } return onLoad } function display(data){ var img = document.createElement('img'); img.src = data; var context = canvas.getContext('2d') context.clearRect(0, 0, WIDTH, HEIGHT); context.drawImage(img, 0, 0, WIDTH, HEIGHT); } function compressCanvas(){ return canvas.toDataURL('image/jpeg', AMOUNT / 100); } function download(data) { function b64toBlob(b64Data, contentType, sliceSize) { contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = atob(b64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } var blob = new Blob(byteArrays, {type: contentType}); return blob; } var chromeApp = Boolean(chrome && chrome.permissions) if (chromeApp){ chrome.fileSystem.chooseEntry({type:'openDirectory'}, function(entry) { chrome.fileSystem.getWritableEntry(entry, function(entry) { entry.getFile('example.jpg', {create:true}, function(entry) { entry.createWriter(function(writer){ writer.write(b64toBlob(data.slice(23), 'image/jpg')) }) }) }) }) } else { let a = document.createElement("a"); a.href = data; a.download = 'downloadExample.jpg' document.body.appendChild(a) a.click(); window.URL.revokeObjectURL(a.href); a.remove() } } .fileInput { display: none; position: absolute; top: 0; right: 0; font-size: 100px; } #clickable-area{ background: #ccc; width: 500px; display: flex; margin-bottom: 50px; } #clickable-area-text{ margin: auto; } .yellow-button { cursor: pointer; color: white; background: #f1c40f; height: 30px; width: 120px; padding: 30px; font-size: 22px; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25); }

Shrink Image

( you can click anywhere in here )  

Stack Overflow limitations seem to prevent the code snippet from actually compressing and downloading the file. The exact same code here shows that the full upload/compress/download process does actually work as intended.


A
Azhar Uddin Sheikh

JS Bin


D
David Mikula

With answers from this question, I fixed what many in coments said doesn¨t work for them which is that it's not showing how many files user chose.

<label for="uploadedFiles" class="btn btn-sm btn-outline-primary">Choose files</label>
<input type="file" name="postedFiles" id="uploadedFiles" multiple="multiple" hidden onchange="javascript:updateList()" />
<input class="btn btn-primary mt-2 btn-action" type="submit" value="Send" formmethod="post" formaction="@Url.Action("Create")" /><br />
<span id="selected-count">Selected files: 0</span>
<script>
    updateList = function () {
        var input = document.getElementById('uploadedFiles');//list of files user uploaded
        var output = document.getElementById('selected-count');//element displaying count
        output.innerHTML = 'Selected files: ' + input.files.length;
    }
</script>

You can easily improve it by showing names of files instead or whatever you wish to do but all I wanted was to inform user that they have already picked files.