search

Home  >  Q&A  >  body text

javascript - How to get files by dragging them to the browser?

If you click to upload on the page, you can click to get the files[0] in the input file;

The current requirement is to drag the image directly from the desktop to the browser. How to get the first file in files[0]?

高洛峰高洛峰2767 days ago748

reply all(1)I'll reply

  • typecho

    typecho2017-06-12 09:27:02

    /**
     * 拖拽实现
     */
    var dropbox = document.getElementById("dropbox");
    
    dropbox.addEventListener("dragenter", function(e){
        e.stopPropagation();
        e.preventDefault();
    }, false);
                
    dropbox.addEventListener("dragover", function(e){
        e.stopPropagation();
        e.preventDefault();
    }, false);
                
    dropbox.addEventListener("drop", function(e){
        e.stopPropagation();
        e.preventDefault();
                
        var dt = e.dataTransfer;
        var files = dt.files;
        
        // files[0]即为第一个文件
          
    }, false);

    For details, please refer to: Selecting files through drag and drop operations

    I also recommend you an example I wrote:
    Select image files - supports three input methods (input box selection, drag and drop selection, screenshot and paste three input methods)

    reply
    0
  • Cancelreply