如何使用 javascript 从文件对话框中捕获文件选择?

How to capture file selection from a file dialog box using javascript?

我使用下面的代码使用 java 脚本创建了一个文件对话框

var input = $(document.createElement('input'));
input.attr("type", "file");
input.trigger('click');

使用以上代码正确显示文件对话框。

如果使用“文件对话框”上的“打开”按钮选择文件,我如何捕获文件名和其他详细信息?

使用已选择的文件我想使用 ajax 请求

将所选文件上传到服务器

我尝试了如下几个选项来捕捉打开按钮的点击。但这没有帮助。有什么建议吗?

input.onchange = function(e) {
alert("File Selected"); 
};  

input.onclick = function(e) {
alert("File Selected");
};

file 输入有一个名为 files 的特殊 属性。您可以按如下方式访问它们(作为一个数组,如果您指定了 multiple 属性):

var files = input.files;

MDN documentation 状态:

An object of this type is returned by the files property of the HTML <input> element; this lets you access the list of files selected with the <input type="file"> element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage.