Table of Contents
Drag events
Prevent default behavior
Get the dragged file
Home Web Front-end JS Tutorial How to control file dragging and obtain dragging content functions in js

How to control file dragging and obtain dragging content functions in js

Jun 05, 2018 pm 05:25 PM
js

This article mainly shares with you the implementation process of using JS to write control files for dragging and obtaining dragging content, as well as code sharing. If you are interested, learn together.

When the user drags a file to an element in the browser, js can monitor the events related to dragging and process the dragging results. This article discusses some issues related to dragging files. problem, but did not deal with too many issues regarding compatibility.

Drag events

The events that js can monitor for drag include drag, dragend, dragenter, dragexit (no browser implementation), dragleave, dragover, dragstart, and drop. The detailed content can be See MDN.

Among them, the events related to dragging files include dragenter (file is dragged in), dragover (file is dragged in suspension), dragleave (file is dragged away), and drop (file is dragged and dropped).

Drag events can be bound to specified DOM elements or to the entire page.

var dropEle = document.querySelector('#dropZone');
dropEle.addEventListener('drop', function (e) {
  // 
}, false);
document.addEventListener('drop', function (e) {
  // 
}, false);
Copy after login

Prevent default behavior

Generally speaking, we only need to write the business logic for handling drag and drop files into the drop event. Why do we need to bind dragenter, dragover, and dragleave? What about these three events?

Because when you drag a file to a browser that does not handle drag events, the browser will open the file. For example, if you drag a picture, the browser will open the picture. When using a PDF reader, you can also drag a PDF into the browser, and the browser will open the PDF file.

If the browser opens the dragged file, the page will jump away. We hope to get the dragged file instead of letting the page jump away. As mentioned above, it is the default behavior of the browser to open the dragged file. If we need to prevent this default behavior, we need to prevent it in the above event.

dropZone.addEventListener("dragenter", function (e) {
  e.preventDefault();
  e.stopPropagation();
}, false);
dropZone.addEventListener("dragover", function (e) {
  e.preventDefault();
  e.stopPropagation();
}, false);
dropZone.addEventListener("dragleave", function (e) {
  e.preventDefault();
  e.stopPropagation();
}, false);
dropZone.addEventListener("drop", function (e) {
  e.preventDefault();
  e.stopPropagation();
  // 处理拖拽文件的逻辑
}
Copy after login

In fact, dragenter does not prevent the default behavior and does not trigger the browser to open files. In order to prevent compatibility issues that some browsers may have, all events in the drag cycle prevent the default behavior and Stopped event bubbling.

Get the dragged file

We will get the file object from the event object in the callback of the drop event.

In the event object, an attribute such as e.dataTransfer, which is a DataTransfer type data, has the following attributes

Attributes TypeDescription
dropEffectStringUsed to hack some compatibility Question
effectAllowedStringNot used for the time being
filesFileListDrag-and-drop file list
itemsDataTransferItemListDrag-and-drop data (may be a string)
typesArrayThe drag data type property is confusing in Safari

在Chrome中我们用items对象获得文件,其他浏览器用files获得文件,主要是为了处理拖拽文件夹的问题,最好不允许用户拖拽文件夹,因为文件夹内可能还有文件夹,递归上传文件会很久,如果不递归查找,只上传目录第一层级的文件,用户可能以为上传功能了,但是没有上传子目录文件,所以还是禁止上传文件夹比较好,后面我会说要怎么处理。

Chrome获取文件

dropZone.addEventListener("drop", function (e) {
  e.preventDefault();
  e.stopPropagation();
  
  var df = e.dataTransfer;
  var dropFiles = []; // 存放拖拽的文件对象
  
  if(df.items !== undefined) {
    // Chrome有items属性,对Chrome的单独处理
    for(var i = 0; i < df.items.length; i++) {
      var item = df.items[i];
      // 用webkitGetAsEntry禁止上传目录
      if(item.kind === "file" && item.webkitGetAsEntry().isFile) {
        var file = item.getAsFile();
        dropFiles.push(file);
      }
    }
  }
}
Copy after login

其他浏览器获取文件

这里只测试了Safari,其他浏览器并没有测试,不过看完本文一定也有思路处理其他浏览器的兼容情况。

dropZone.addEventListener("drop", function (e) {
  e.preventDefault();
  e.stopPropagation();
  
  var df = e.dataTransfer;
  var dropFiles = []; // 存放拖拽的文件对象
  
  if(df.items !== undefined) {
    // Chrome拖拽文件逻辑
  } else {
    for(var i = 0; i < df.files.length; i++) {
      dropFiles.push(df.files[i]);
    }
  }
}
Copy after login

由于Safari没有item,自然也没有webkitGetAsEntry,所以在Safari无法确定拖拽的是否是文件还是文件夹。

非Chrome内核浏览器判断目录的方法

浏览器获取到的每个file对象有四个属性:lastModified、name、size、type,其中type是文件的MIME Type,文件夹的type是空的,但是有些文件没有MIME Type,如果按照type是否为空判断是不是拖拽的文件夹的话,会误伤一部分文件,所以这个方法行。

那么还有什么方法可以判断呢,思路大概是这样子的,用户拖拽的文件和文件夹应该是不一样的东西,用File API操作的时候应该会有区别,比如进行某些操作的时候,文件就能够正常操作,但是文件夹就会报错,通过错误的捕获就能够判断是文件还是文件夹了,好我们根据这个思路来写一下。

dropZone.addEventListener("drop", function (e) {
  e.preventDefault();
  e.stopPropagation();
  var df = e.dataTransfer;
  var dropFiles = [];
  
  if(df.items !== undefined){
    // Chrome拖拽文件逻辑
  } else {
    for(var i = 0; i < df.files.length; i++){
      var dropFile = df.files[i];
      if ( dropFile.type ) {
        // 如果type不是空串,一定是文件
        dropFiles.push(dropFile);
      } else {
        try {
          var fileReader = new FileReader();
          fileReader.readAsDataURL(dropFile.slice(0, 3));
          fileReader.addEventListener(&#39;load&#39;, function (e) {
            console.log(e, &#39;load&#39;);
            dropFiles.push(dropFile);
          }, false);
          fileReader.addEventListener(&#39;error&#39;, function (e) {
            console.log(e, &#39;error,不可以上传文件夹&#39;);
          }, false);
        } catch (e) {
          console.log(e, &#39;catch error,不可以上传文件夹&#39;);
        }
      }
    }
  }
}, false);
Copy after login

上面代码创建了一个FileReader实例,通过这个实例对文件进行读取,我测试读取一个1G多的文件要3S多,时间有点长,就用slice截取了前3个字符,为什么是前3个不是前2个或者前4个呢,因为代码是我写的,我开心这么写呗~

如果load事件触发了,就说明拖拽过来的东西是文件,如果error事件触发了,就说明是文件夹,为了防止其他可能的潜在错误,用try包起来这段代码。

三方应用的一点点小hack

经过测试发现通过Mac的Finder拖拽文件没有问题,但是有时候文件并不一定在Finder中,也可能在某些应用中,有一个应用叫做圈点,这个应用的用户反馈文件拖拽失效,去看了其他开源文件上传的源码,发现了这样一行代码:

dropZone.addEventListener("dragover", function (e) {
  e.dataTransfer.dropEffect = &#39;copy&#39;; // 兼容某些三方应用,如圈点
  e.preventDefault();
  e.stopPropagation();
}, false);
Copy after login

需要把dropEffect置为copy,上网搜了下这个问题,源码文档中也没有说为什么要加这个,有兴趣的同学可以找一下为什么。

可以拿来就用的代码

由于用了FileReader去读取文件,这是一个异步IO操作,为了记录当前处理了多少个文件,以及什么时候触发拖拽结束的回调,写了一个checkDropFinish的方法一直去比较处理的文件数量和文件总数,确定所有文件处理完了后就去调用完成的回调。

另外,我在最后调试异步处理的时候,用的断点调试,发现断点调试在Safari中会导致异步回调不触发,需要自己调试定制功能的同学注意下。

// 获得拖拽文件的回调函数
function getDropFileCallBack (dropFiles) {
  console.log(dropFiles, dropFiles.length);
}
var dropZone = document.querySelector("#dropZone");
dropZone.addEventListener("dragenter", function (e) {
  e.preventDefault();
  e.stopPropagation();
}, false);
dropZone.addEventListener("dragover", function (e) {
  e.dataTransfer.dropEffect = &#39;copy&#39;; // 兼容某些三方应用,如圈点
  e.preventDefault();
  e.stopPropagation();
}, false);
dropZone.addEventListener("dragleave", function (e) {
  e.preventDefault();
  e.stopPropagation();
}, false);
dropZone.addEventListener("drop", function (e) {
  e.preventDefault();
  e.stopPropagation();
  var df = e.dataTransfer;
  var dropFiles = []; // 拖拽的文件,会放到这里
  var dealFileCnt = 0; // 读取文件是个异步的过程,需要记录处理了多少个文件了
  var allFileLen = df.files.length; // 所有的文件的数量,给非Chrome浏览器使用的变量
  // 检测是否已经把所有的文件都遍历过了
  function checkDropFinish () {
    if ( dealFileCnt === allFileLen-1 ) {
      getDropFileCallBack(dropFiles);
    }
    dealFileCnt++;
  }
  if(df.items !== undefined){
    // Chrome拖拽文件逻辑
    for(var i = 0; i < df.items.length; i++) {
      var item = df.items[i];
      if(item.kind === "file" && item.webkitGetAsEntry().isFile) {
        var file = item.getAsFile();
        dropFiles.push(file);
        console.log(file);
      }
    }
  } else {
    // 非Chrome拖拽文件逻辑
    for(var i = 0; i < allFileLen; i++) {
      var dropFile = df.files[i];
      if ( dropFile.type ) {
        dropFiles.push(dropFile);
        checkDropFinish();
      } else {
        try {
          var fileReader = new FileReader();
          fileReader.readAsDataURL(dropFile.slice(0, 3));
          fileReader.addEventListener('load', function (e) {
            console.log(e, 'load');
            dropFiles.push(dropFile);
            checkDropFinish();
          }, false);
          fileReader.addEventListener('error', function (e) {
            console.log(e, 'error,不可以上传文件夹');
            checkDropFinish();
          }, false);
        } catch (e) {
          console.log(e, 'catch error,不可以上传文件夹');
          checkDropFinish();
        }
      }
    }
  }
}, false);
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

vue注册组件的几种方式总结

Vue.js自定义事件的表单输入组件方法

layui之select的option叠加问题的解决方法

The above is the detailed content of How to control file dragging and obtain dragging content functions in js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles