Javascript 以编程方式设置 type="file" 输入 HTML 元素的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6021526/
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
Programmatically set the value of a type="file" input HTML element?
提问by Juan
Note:
The answer(s) 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 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)?
笔记:
下面的答案反映了 2009 年旧浏览器的状态。 现在您实际上可以在 2017 年使用 JavaScript 以动态/编程方式设置文件输入元素的值。
有关详细信息以及演示,请参阅此问题中的答案:
如何以编程方式设置文件输入值(即:拖放文件时)?
What I need to do is to programmatically send a POST request to a service from javascript code from an application that uses a .NET WebBrowser
, which is basically an embedded Internet Explorer. This service requires one of the fields to be a "file".
我需要做的是从使用 .NET 的应用程序WebBrowser
(基本上是嵌入式 Internet Explorer)中的JavaScript 代码以编程方式向服务发送 POST 请求。此服务要求字段之一是“文件”。
So either, is there any way to set the value of a "file" input in a form, given that I have the contentof the file, such as in an array of bytes (and not the path of the file; I'm not trying to steal files from users here :) ).
那么,有没有办法在表单中设置“文件”输入的值,前提是我有文件的内容,例如字节数组(而不是文件的路径;我是不要试图从这里的用户那里窃取文件:))。
Or perhaps a way to explicitly create and send the POST request instead of creating a FORM dynamically?
或者也许是一种显式创建和发送 POST 请求而不是动态创建 FORM 的方法?
I need to use JavaScript code that will be run in my WebBrowser
(think IE). Is this possible?
我需要使用将在我的WebBrowser
(想想 IE)中运行的 JavaScript 代码。这可能吗?
采纳答案by Chris Kooken
Unfortunately this is not possible as it would be a security issue. Javascript control over file input fields is very limited. Otherwise people could use this to steal files from user's computers.
不幸的是,这是不可能的,因为这将是一个安全问题。Javascript 对文件输入字段的控制非常有限。否则人们可以使用它从用户的计算机中窃取文件。
Since you have control over the browser, you can send the file using a normal HTTPWebRequest, but it can't be done in JavaScript.
由于您可以控制浏览器,因此您可以使用普通的 HTTPWebRequest 发送文件,但不能在 JavaScript 中完成。