javascript 如何设置文本框值以使用javascript上传文件名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26396468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:54:46  来源:igfitidea点击:

how to set text box value to upload filename using javascript?

javascripthtmlfileuploadtextbox

提问by javasundaram

how to set textbox value based on uploaded filename value.for example i'm upload file like test.zip same value affect in text box the below code am try but not get solution?

如何根据上传的文件名值设置文本框值。例如,我正在上传文件,如 test.zip 相同的值影响文本框下面的代码我尝试但没有得到解决方案?

var filename= document.getElementById("file").value;
    <form>
     File: <input type="file" id="file" name="file"/>
     Upload File : <input type="text" value="'+filename+'"/>
    </form>

采纳答案by Choco

Use some thing like this

使用这样的东西

  <script>
   function setfilename(val)
  {
    var fileName = val.substr(val.lastIndexOf("\")+1, val.length);
   document.getElementById("filename").value = fileName;
  }
</script>
    <form>
     File: <input type="file" id="file" name="file" onchange="setfilename(this.value);"/>
     Upload File : <input type="text"  id="filename"/>
    </form>

回答by ????? ?????

You can get names of files by accessing files object of fileUpload like

您可以通过访问 fileUpload 的 files 对象来获取文件的名称,例如

document.getElementById("file").files[0].name

Assign this value to your text field onChangeevent of fileInputlike this

这个值分配给你的文本字段onChange的情况下fileInput这样

document.getElementById("filename").value = document.getElementById("file").files[0].name;

will set first file name into your field with id filename

将使用 id 将第一个文件名设置到您的字段中 filename

Getting value attribute of file input directly will get you fake file path like C:\fakepath\yourfilename.ext

直接获取文件输入的值属性会让你得到假文件路径,比如 C:\fakepath\yourfilename.ext

回答by dfsq

You need to listen onchangeevent of the file field and when it occurs you write the value to another text input.

您需要监听onchange文件字段的事件,当它发生时,您将值写入另一个文本输入。

var file = document.getElementById("file");
file.onchange = function() {
    document.getElementById('filename').value = file.value;
};

Where I set an id for the text field also:

我还为文本字段设置了 id:

Upload File : <input type="text" id="filename" value="'+filename+'"/>

However note, that the value you can retrieve from file input is not realbut has a fake path due to security considerations. If you need only filename part of the full path you can split it by /character ad take the last piece.

但是请注意,出于安全考虑,您可以从文件输入中检索的值不是真实的,而是具有虚假路径。如果您只需要完整路径的文件名部分,您可以按/字符拆分它并取最后一部分。