如何使用 JavaScript 在没有提交按钮的情况下提交“文件”输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1904168/
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
How do I submit a "file" input without submit button using JavaScript?
提问by Pennywise83
There is a way to automatically submit a form without clicking to a "submit" button?
有没有办法在不点击“提交”按钮的情况下自动提交表单?
I have a form with one "file" input. I would submit the form after the user have selected one file.
我有一个带有一个“文件”输入的表单。我会在用户选择一个文件后提交表单。
回答by Marius
yes, you can use the form.submit()function. Add an onchange listener on the file input and link it to the form.submit()function, like so:
是的,您可以使用该form.submit()功能。在文件输入上添加一个 onchange 侦听器并将其链接到form.submit()函数,如下所示:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" onchange="this.form.submit()" name="myFile"/>
</form>
回答by Pekka
Yes, you can add the following to the onchangeevent of the file input:
是的,您可以将以下内容添加到onchange文件输入的事件中:
<input type='file' .... onchange='this.form.submit();'>
this submits the form right after the user has picked a file. However, the user can't correct a mistaken selection before submitting - be sure to check whether this is really wise.
这会在用户选择文件后立即提交表单。但是,用户在提交之前不能更正错误的选择——一定要检查这是否真的明智。
回答by cwtuan
This solution works for me.
这个解决方案对我有用。
<form enctype="multipart/form-data" method="POST" action="/upload">
<input id="myfilefield" type="file" name="file">
<input type="submit">
</form>
document.getElementById('myfilefield').onchange = function() {
this.form.submit();
};
By the way, you don't need to use flash. Gmail do it by XHR Level 2.
顺便说一下,您不需要使用闪光灯。Gmail 通过 XHR 级别 2 做到这一点。
回答by ceejayoz
I don't believe you can do this. Browsers are very, very strict about what you can do to file upload fields, because of the potential for abuse. If the user accidentally selects a private file, they wouldn't want it to immediately start uploading that file to a random server.
我不相信你能做到这一点。由于存在滥用的可能性,浏览器对您可以对文件上传字段执行的操作非常严格。如果用户不小心选择了一个私人文件,他们不希望它立即开始将该文件上传到随机服务器。
回答by RichieHindle
I'm not sure what the restrictions are with doing this in an HTML form.
我不确定在 HTML 表单中执行此操作有什么限制。
You can, however, do it with Flash. Gmail does it - when I click "Attach a file", I get prompted with a file browse dialog, and when I OK that dialog the upload begins immediately, and also gives me a progress bar.
但是,您可以使用 Flash 来实现。Gmail 做到了 - 当我单击“附加文件”时,我会收到一个文件浏览对话框的提示,当我确定该对话框时,上传立即开始,并且还给了我一个进度条。
Googling for "Flash uploader" will give you many options, but I don't have experience with any of them.
谷歌搜索“Flash 上传器”会给你很多选择,但我没有任何经验。

