如何在jquery中使用拖放上传时区分文件和文件夹?
如果用户尝试将文件夹拖放到我的文件上传器控件中进行上传,那么我需要向用户显示一条错误消息,说明只能上传文件。问题是我无法区分文件和文件夹。
我想到的一种方法是检查 jQuery 的文件类型属性。假设文件名是“test.txt”,则文件类型将返回“text/plain”。对于普通文件夹名称(如“TestFolder”),文件类型将为空,文件大小将返回 0。但是,如果文件夹名称包含“TestFolder.txt”等扩展名,则文件类型将返回“text/plain”。
因此,我可以检查文件类型和文件大小,但对于“TestFolder.txt”之类的文件夹名称,它无法正常工作。有人可以建议我一个好的解决方案来使用 jQuery 或其他方法解决这个问题吗?
If a user tries to drag and drop a folder to my file uploader control for uploading it, then I need to show an error message to the user saying that only files can be uploaded. The problem is I couldn't distinguish a file from a folder.
One way I thought was to check for file type property of jQuery. Supposing that the name of the file is "test.txt", then file type would return "text/plain". For a normal folder name such as "TestFolder", file type would be blank and its file size would return 0. However if the folder name included an extension like "TestFolder.txt", then file type would return "text/plain".
So I could have checked for file type and file size but it would not work correctly for folder name like "TestFolder.txt". Could any one suggest me a good solution to fix this using jQuery or other methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确定文件夹是否已删除的能力取决于用户代理对文件系统的支持API。如果用户代理支持文件系统 API(目前仅 Chrome 21+),您可以使用
Entry
接口,该接口有两个子接口:DirectoryEntry
和>文件条目
。该接口本身具有isDirectory
和isFile
函数。如果不支持此接口,则在检查DataTransfer
对象时无法确定放置的项目是否为文件夹。The ability to determine if a folder has been dropped is dependent on the user agent's support of the Filesystem API. If the user agent DOES support the Filesystem API (currently only Chrome 21+), you can make use of the
Entry
interface, which has two child interfaces:DirectoryEntry
andFileEntry
. The interface itself hasisDirectory
andisFile
functions. Without support for this interface, there is no way to determine if dropped items are folders when examining theDataTransfer
object.由于您不允许拖放文件夹,因此首先检查它是文件夹还是文件,其次检查它是否不是文件夹,然后检查文件扩展名。但IE< 11.不支持文件API来处理。希望有帮助。
Since you are not going to allow folder to drag and drop, first check if it's folder or file, second only if it's not folder then check for file extension. But IE < 11 does not support file API to handle. Hope it helps.
据我所知,出于安全目的,浏览器(以及本质上的 JavaScript)无法访问任何文件访问方法,因此您无法检查文件的实际内容。
我过去自己也曾处理过这个问题,我发现最好的选择是在服务器端处理文件,并在上传完成后将错误返回到页面。
不过,我很高兴自己能看到更好的选择。
As far as I'm aware the browser (And javascript inherently) doesn't have access to any file access methodologies for security purposes so you cannot check what the file actually is.
I have worked with this problem myself in the past and the best option I have found that works is to handle the file server-side, and return the error back to the page after upload has completed.
I would be happy to see better alternatives myself though.