Home  >  Article  >  Web Front-end  >  Implementation and principle introduction of JavaScript drag and drop upload function

Implementation and principle introduction of JavaScript drag and drop upload function

不言
不言forward
2019-02-19 15:55:454071browse

This article brings you an introduction to the implementation and principles of the JavaScript drag-and-drop upload function. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Recently, Xiao Ming encountered such a situation: when uploading files on the web page, the page would occasionally crash. Xiao Ming carefully tested this situation and found that a file upload component used before had some flaws, so Xiao Ming decided to handwrite one by himself, with the following style:

Implementation and principle introduction of JavaScript drag and drop upload function

Implementation and principle introduction of JavaScript drag and drop upload function

##Figure 1 shows the style when no files are uploaded, and Figure 2 shows the style after uploading files. The dotted line part is the placement area. Let’s look at the code first:

html part

<div>
    <div>
      <div>
        <div>{{ fileName }}</div>
        <div>
          <span>将文件拖拽至此,或</span>
          <label>点此上传</label>
        </div>
      </div>
    </div>

    <div>
      <input>
      <label>选择文件</label>

      <button>提交</button>
    </div>
  </div>

css part

    * {
      font-size: 14px;
    }
    .drag-area {
      height: 200px;
      width: 300px;
      border: dashed 1px gray;
      margin-bottom: 10px;
      color: #777;
    }
    .uploader-tips {
      text-align: center;
      height: 200px;
      line-height: 200px;
    }
    .file-name {
      text-align: center;
      height: 200px;
      line-height: 200px;
    }

js part

    new Vue({
      el: '#app',
      data () {
        return {
          fileName: '',
          batchFile: '',
          MAX_FILE_SIZE: 10 * 1000 * 1000
        }
      },
      methods: {
        // 点击上传
        chooseUploadFile (e) {
          const file = e.target.files.item(0)

          if (!file) return
          if (file.size > this.MAX_FILE_SIZE) {
            return alert('文件大小不能超过10M')
          }

          this.batchFile = file
          this.fileName = file.name

          // 清空,防止上传后再上传没有反应
          e.target.value = ''
        },
        // 拖拽上传
        fileDragover (e) {
          e.preventDefault()
        },
        fileDrop (e) {
          e.preventDefault()
          const file = e.dataTransfer.files[0] // 获取到第一个上传的文件对象

          if (!file) return
          if (file.size > this.MAX_FILE_SIZE) {
            return alert('文件大小不能超过10M')
          }

          this.batchFile = file
          this.fileName = file.name
        },
        // 提交
        uploadOk () {
          if (this.batchFile === '') {
            return alert('请选择要上传的文件')
          }

          let data = new FormData()
          data.append('upfile', this.batchFile)

          // ajax
        }
      }
    })

Core principle description

  • dragover and drop events

One thing to talk about is these two events in drag and drop, because these two events support the core function of drag and drop upload.

For the dragging action, there are two core concepts, one is
drag element, and the other is placement target. Here, I will only talk about the events on the drop target. For the events of the drag element, please check it yourself.

What events does it have for placing targets? As follows:

When an element is dragged to a valid drop target (such as the dotted area in the above example), the following events will occur in sequence:
(1) dragenter
(2) dragover
(3) dragleave or drop
As long as an element is dragged to the drop target, the dragenter event will be triggered (similar to the mouseover event). The dragover event follows immediately and continues to fire while the dragged element is moving within the drop target. If the element is dragged outside the drop target, the dragover event no longer occurs, but the dragleave event is fired (similar to the mouseout event). If the element is dropped into the drop target, the drop event is fired instead of the dragleave event.

For this example, we only need to pay attention to the dragover and drop events. But the drop event is a bit naughty. If you want to listen to it, you have to do some processing, because by default, elements are not allowed to be placed. When dragging an element past some invalid placement targets, you can see a special cursor. (There is a backslash in the circle), indicating that it cannot be placed. As follows:

Implementation and principle introduction of JavaScript drag and drop upload function

#If the dragged element passes through an element that is not allowed to be placed, no matter how the user operates, the drop event will not occur. then what should we do?

We can override the default behavior of the dragover event, such as e.preventDefault() in the above example code.
Careful students may want to ask, there is also e.preventDefault() in the drop event, can it be removed? You can try it yourself.

  • dataTransfer object

This object may look a little strange, but its role is not small. For example, if you drag a picture to the target area, how does the target area obtain the information of the picture? Just rely on it! It is a property of the event object that is used to pass data in string format from the dragged element to the drop target. In this example, we can use it to get the file information being dragged.

  • Input change event

This event actually has a pitfall. It has such a feature, that is: uploading the same file does not The change event will be triggered even if the file content has been modified.

It’s scary to think about it! For example, if the user wants to upload a document, but after dragging it to the dotted area, he finds that the document content needs to be modified. After he completes the modification, he drags the document and then submits it to the server. Then the document content he uploads to the server is unmodified. previous!
So, we need the code e.target.value = '' to perform reset processing, so that the change event will be triggered every time a file is uploaded.


The above is the detailed content of Implementation and principle introduction of JavaScript drag and drop upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete