如何从文件系统

时间:2016-02-05 07:36:03

标签: html javascript-events drag-and-drop droppable

我正在尝试在我的应用程序中实现拖放操作,这需要删除文件夹的完整路径。

我做过类似的事情

<html>
<head>
<style>
#dropzone {
    height:200px;
    width: 200px;
    border: 10px dashed #0c0;
    background-color:cyan;
}
</style>                  
</head>
<body>

<div id="dropzone" droppable="true" ondrop ="drop(event)" ondragenter="return false" ondragover="return false">
</div>

<script type="text/javascript">  
function drop(e) {
    e.stopPropagation();
    e.preventDefault();
    var length = e.dataTransfer.items.length;
    for (var i = 0; i < length; i++) {
        var entry = e.dataTransfer.items[i].webkitGetAsEntry();
        if (entry.isDirectory) {
            alert(entry);//here i need to get path of folder being dropped.
        }
    }
}
</script>
</body>
</html

如果我在e.dataTransfer.files[i].name内警告for loop,那么它只显示文件夹的名称,但不显示其路径。

javascript是否允许访问本地文件系统?或者任何解决方法。

3 个答案:

答案 0 :(得分:1)

  

javascript是否允许访问本地文件系统?###

短吻...... :不。

  

那么如何获取已删除文件夹的完整路径?

这很容易,您需要做的就是将删除的项目作为文件

  

它有什么变化?

在上面的代码中,您有e.dataTransfer.items[i].webkitGetAsEntry()

webkitGetAsEntry()方法非常有用,因为它返回''Entry''对象。你可以做很酷的事情,例如:

  • 检查条目是文件还是目录。

现在, getAsFile()方法返回一个文件对象,其中包含与实际文件相关的所有好东西。看看下面的代码(我修改了你的代码)。

代码:

/*
 *  Store your data for an easy access.
 */ 
var items  = e.dataTransfer.items;

/*
 *  Loop through items.
 */
for (var i = 0; i < items.length; i++) 
{
    // Get the dropped item as a 'webkit entry'.
    var entry = items[i].webkitGetAsEntry();

    if (entry.isDirectory) 
    {
        /*
         *  getAsFile() returns a File object that contains
         *  some useful informations on the file/folder that has 
         *  been dropped.
         *
         *  You get the following properties :
         *    - lastModified (timestamp)
         *    - lastModifiedDate
         *    - name (...of the file)
         *    - path (fullpath)
         *    - size
         *    - type
         *    - etc. (...some other properties and methods)
         *
         *  So you can do the following to retrieve the path of the 
         *  dropped folder.
         */
        alert(items[i].getAsFile().path);
    }
}

甚至更简单:

var items  = e.dataTransfer.items;      // -- Items

for (var i = 0; i < items.length; i++) 
{
    // Get the dropped item as a 'webkit entry'.
    var entry = items[i].webkitGetAsEntry();

    // Get the same dropped item, but as a File.
    var file = items[i].getAsFile();

    if (entry.isDirectory) 
    {
        alert(file.path);
    }
}

如您所见,没有什么能阻止您同时使用。您将获得''Entry''对象以检查您是否正在处理文件夹或文件,然后您可以使用 getAsFile()方法来访问相关信息丢弃的项目(如路径)。

希望它有所帮助!

答案 1 :(得分:1)

  • getAsFile 公开路径属性。 - 不在Chrome中 - 在IE中,甚至不支持dataTransfer.items。

答案 2 :(得分:-4)

尝试

e.dataTransfer.files[0].path

将为您提供文件夹路径。

相关问题