如何在HTML中设置文件输入的值?

2024-04-25 00:35:14 发布

您现在位置:Python中文网/ 问答频道 /正文

Note:

The answers & comments below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript and a dataTransfer or FileList object in 2017.

See the answer in this question for details as well as a demo:
How to set file input value programatically (i.e.: when drag-dropping files)?

如何设置此值?

<input type="file" />

Tags: oftheininputvalueascommentsbelow
3条回答

你不能

设置文件输入值的唯一方法是由用户选择文件。

这是出于安全考虑。否则,您将能够创建一个Javascript,自动从客户端计算机上载特定文件。

不是对你的问题的回答(其他人已经回答了),但是如果你想拥有上传文件字段的一些编辑功能,你可能需要做的是:

  • 只需打印文件名或URL、可单击的下载链接或图像,即可显示此字段的当前值:只需显示它,可能是缩略图
  • 上载新文件的<input>标记
  • 选中时删除当前上载文件的复选框。请注意,无法上载“空”文件,因此需要这样的内容来清除字段的值

你不能因为安全原因。

想象一下:

<form name="foo" method="post" enctype="multipart/form-data">
    <input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>

你不希望你访问的网站能够做到这一点,是吗?=)

相关问题 更多 >