How can you detect that a user dragged a folder (not a file) into their browser?

萝らか妹 提交于 2019-12-10 16:33:07

问题


I know very well that you are not allowed to upload a whole folder via drag and drop. The problem is, how can I tell if someone tries to do it? If you drag a folder into the browser, it behaves exactly as if you dragged a file with some extension webkit doesn't know about, like '.sh'. How can you tell the difference?

I have tested this in Chrome and Safari and Firefox on Mac OS X and Windows. Depending on the browser and OS, I get slightly different results. Sometimes it succeeds in uploading a zero-byte file. Sometimes it uploads a picture of a folder. Sometimes it fails to upload anything.

event.dataTransfer.types and event.dataTransfer.items both lie and say the type is "File" or "file" respectively.

Firefox gives this list of types:

{"0":"application/x-moz-file","1":"text/x-moz-url","2":"text/plain","3":"Files"}

回答1:


I found a way to do it. The information can be found in dataTransfer.items via getAsEntry, though it's a little different in different browsers. Also, this doesn't have a pointer back to the file you wanted, though you can figure it out based on the file name assuming you're not uploading two files with the same name at the same time. There's not really much to work with here, so this is the best I could do.

just_the_files = (dataTransfer) ->
    real_files_set = {}
    for item in dataTransfer.items
        entry = item.getAsEntry?() or item.webkitGetAsEntry?() or item
        if entry.isFile
            real_files_set[entry.name] = true
     (file for file in dataTransfer.files when file.name of real_files_set)



回答2:


actually when you drag a folder on to a browser, all of folders and files thats in the folder that you drag will be showed..

for example in chrome

it will show "Index of D:\my documents\Downloads\" and the name, size and the date you modifies the file...




回答3:


In FF there is a method for dataTransfer: mozGetDataAt(type, index), when I use type 'text/x-moz-url', it returns the file's path like 'files:///D:/abc/fileName'. And its funny that a folder/directive has a path with '/' at the end like 'files:///D:/abc/folder1/'. I wonder if it works in this situation?



来源:https://stackoverflow.com/questions/12612237/how-can-you-detect-that-a-user-dragged-a-folder-not-a-file-into-their-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!