javascript 如何在文本框中写入要上传的文件的路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4640082/
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-25 14:23:39  来源:igfitidea点击:

How to write the Path of a file to upload in a text box?

javascripthtmlfile-upload

提问by Florian Müller

Little question: I'm trying to create a Form to upload a file.

小问题:我正在尝试创建一个表单来上传文件。

Now i got a button to select the file and a submit button.

现在我有一个按钮来选择文件和一个提交按钮。

How can i design it like if i've selected a file, the path of it (C:\Users....) is shown in a textbox?`

如果我选择了一个文件,我该如何设计它,它的路径 (C:\Users....) 显示在文本框中?`

Thx for help

谢谢你的帮助

回答by Shadow Wizard is Ear For You

To copy the selected file name/path to different text box, first have this JS:

要将选定的文件名/路径复制到不同的文本框,首先要有这个 JS:

function CopyMe(oFileInput, sTargetID) {
    document.getElementById(sTargetID).value = oFileInput.value;
}

And it will work with such HTML:

它将与这样的 HTML 一起使用:

<div>
    <input type="file" onchange="CopyMe(this, 'txtFileName');" />
</div>
<div>
    You chose: <input id="txtFileName" type="text" readonly="readonly" />
</div>

Test case: http://jsfiddle.net/yahavbr/gP7Bz/

测试用例:http: //jsfiddle.net/yahavbr/gP7Bz/

Note that modern browsers will hide the real full path showing something like C:\fakepath\realname.txtso to show only the name (which is real) change to:

请注意,现代浏览器会隐藏真实的完整路径,显示类似C:\fakepath\realname.txt这样的内容,只显示名称(真实的)更改为:

function CopyMe(oFileInput, sTargetID) {
    var arrTemp = oFileInput.value.split('\');
    document.getElementById(sTargetID).value = arrTemp[arrTemp.length - 1];
}

(http://jsfiddle.net/yahavbr/gP7Bz/1/)

http://jsfiddle.net/yahavbr/gP7Bz/1/

回答by Quentin

If you want to upload a file, use <input type="file" …>and it will come with it's own button. Don't forget to set the enctype.

如果你想上传一个文件,使用<input type="file" …>它会带有它自己的按钮。不要忘记设置enctype

A regular text box won't let you upload files.

常规文本框不会让您上传文件。

回答by kark

The <input type="file"..>will not show textbox in chrome and safri browser, we can configure the display styles by CSS itself, go to the link here

<input type="file"..>不会显示在浏览器和浏览器safri文本框,我们可以通过配置CSS本身的显示风格,可以进入该链接在这里