当用户通过<input type =“file"选择文件时如何获取文件名/>? [英] How to get file name when user select a file via <input type="file" />?
问题描述
我之前见过类似的问题,但出于安全原因,最终没有解决方案.
I've seen similar questions before,which ends up with no solution,because of security reasons.
但是今天我看到 hostmonster 已经成功地实现了这一点,当我打开一张票并在他们的后端附加一个文件时.
But today I see hostmonster has successfully implemented this,when I open a ticket and attach a file in their backend.
它适用于 Firefox 和 IE(确切地说是版本 8).
It works both with firefox and IE(version 8 to be exact).
我已经验证它完全是客户端脚本,没有发送请求(使用萤火虫).
I've verified it's exactly client side scripting,no request is sent(with firebug).
现在,我们可以重新考虑这个问题吗?
Now,can we re-consider this question?
推荐答案
您可以获得文件名,但无法获得完整的客户端文件系统路径.
You can get the file name, but you cannot get the full client file-system path.
尝试在 change
事件中访问文件 input
的 value
属性.
Try to access to the value
attribute of your file input
on the change
event.
大多数浏览器只会给你文件名,但也有像IE8这样的例外,它会给你一个假路径,比如:"C:fakepathmyfile.ext"
和旧版本 (IE <= 6) 实际上会给你完整的客户端文件系统路径(由于它缺乏安全性).
Most browsers will give you only the file name, but there are exceptions like IE8 which will give you a fake path like: "C:fakepathmyfile.ext"
and older versions (IE <= 6) which actually will give you the full client file-system path (due its lack of security).
document.getElementById('fileInput').onchange = function () {
alert('Selected file: ' + this.value);
};
这篇关于当用户通过<input type =“file"选择文件时如何获取文件名/>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!