如何更改<input type="file" />按钮的文本?

328
<input type="file" value="Browse" name="avatar" id="id_avatar" />

我尝试修改value,但它没有起作用。如何自定义按钮文本?


你是在说文件名还是按钮文本? - Artelius
可能是如何重命名HTML“浏览”按钮?的重复问题。 - Ciro Santilli OurBigBook.com
请返回已翻译的文本:相关:https://dev59.com/d3VC5IYBdhLWcg3wsTbv - djvg
1
现在有像::file-selector-button这样的伪元素。也许可以以某种方式使用它们。 - Sebastian Simon
24个回答

0

如果你在使用Rails时遇到问题,我想从@Fernando Kosh发布的原始答案中添加一些提示

  • 下载文件zip并将文件bootstrap-filestyle.min.js复制到文件夹app/assets/javascripts/中
  • 打开你的application.js并在下面添加这行代码

    //= require bootstrap-filestyle.min

  • 打开你的coffee并添加这行代码

    $(":file").filestyle({buttonName: "btn-primary",buttonBefore: true,buttonText: " 在此处输入您的文本",icon: false});


0

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;">


0
扩展Ken Karlo的解决方案以回答Ragnar的问题。
对于React,我通过useState来更改文本,像这样:
import { FC, useState } from 'react'
import classNames from 'classnames' // classNames to organize the classes.
import { ComponentPropsWithRef } from 'react'

type Props = ComponentPropsWithRef<'input'>

const UIPanel: FC<Props> = (props) => {
  const [files, setFiles] = useState<any[]>([])

  const handleFileChange = (event: any) => {
    let cfiles:any[] = event.target.files
    setFiles(files => cfiles)
  }

  let displayText = "Whatever text you want"
  return (
    <>
      <label class="btn btn-primary">
        <span>
        {displayText}  <span style="color:darkgrey" >{files && files.length > 0 ? (files?.length) + " files":"No file chosen"}</span>
        </span>
        <input onChange={(e) => handleFileChange(e)}
                type="file"
                buttonSize="small"
                displayText="Choose Locales Folder"
                files={files}
                webkitdirectory=""
                directory=""
                multiple
                className={classNames('hidden')}
        />
      </label>
    </>
  )
}


我正在更改唯一的files.length部分以模仿原始部分,同样,您也可以更改displayText变量以更改按钮上的指示文本。
附注:我的用例是上传一个文件夹,这就是为什么您看到webkitdirectorydirectorymultiple,如果您的用例是单个文件,您可以相应地进行更改。

-1

这是一个可能对您有帮助的替代方案。它隐藏了出现在按钮外部的文本,并将其与 div 的背景颜色混合。然后,您可以为 div 设置所需的标题。

<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>

在Chrome 39中,我看到了“上传图片”文本和<input>按钮。也许自你发布这篇文章以来,Chrome对文件输入的处理方式已经发生了变化? - EricP
1
@yan-bellavance 你在做什么?如果你认为某个答案不正确或无帮助,请投反对票,但绝不能损坏它! - Kaiido

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接