简体   繁体   English

有没有办法限制输入类型文件中的字符数

[英]Is there a way to limit number of characters in input type file

我有一个类型文件的输入,我的问题是:在我选择文件后,文件名是否可以限制为一定数量的字符?

You can get the file name using 您可以使用获取文件名

var filename = document.getElementById('file-id').value;
filename = filename.replace(/^.*[\\\/]/, '');

But limitation in sense, after uploading the file you can get the file name using above approach. 但在意义上的限制,上传文件后,您可以使用上述方法获取文件名。

Then you can have 然后你可以拥有

if (filename.length < 100 ) {
  //do something
}

FYI: Evert thing happens only after the file being uploaded in client side. 仅供参考:只有在客户端上传文件后才会发生Evert事件。 There is no use in limiting the filepath before uploaded to server. 在上传到服务器之前限制文件路径是没有用的。

Do you mean like this? 你的意思是这样的吗?

var limit = 8;

var fileName = document.getElementById("file-name-field").value();

// get both parts
var fileNameExtension = "." + fileName.split(".").pop();
var fileNameBase = fileName.substring(0, fileName.length()-fileNameExtension.length());

if(fileNameBase.length()>limit){
    // now limit it and set it as fileName
    fileName = fileNameBase.substring(0, limit) + fileNameExtension;
}

Most browsers don't allow modification of the value attribute of file fields. 大多数浏览器不允许修改文件字段的value属性。 It's a security hole, because it would allow a malicious page to retrieve an arbitrary file using a hidden field. 这是一个安全漏洞,因为它允许恶意页面使用隐藏字段检索任意文件。

Please try following JavaScript to check length of the file name. 请尝试使用JavaScript来检查文件名的长度。

function valueCheck()
{
 var filePath = document.getElementById("file").value;
 var fileName = filePath.replace(/[^\\\/]+$/, "");
    if(fileName !=null && fileName.length >10)
    {
        alert('Filename if bigger');
    }
}

Demo URL : http://jsfiddle.net/BhaveshKachhadiya/6EPvg/6/ 演示网址: http//jsfiddle.net/BhaveshKachhadiya/6EPvg/6/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM