Drag and drop image(s) from desktop to browser instead of searching via input

廉价感情. 提交于 2019-12-07 17:49:21

问题


I'll be honest, way out of my depth here so any help or guidance would be great.

I have a very basic input form that allows me to choose multiple images from local folders and display them on the page as well as display info such as file type/name/size.

I'd like to be able to drag and drop images into the page, rather than manually search for the images each time. This is where I'm stuck. I have no idea what I need to google to get my desired result. I've seen a lot around the file API that I genuinely don't really understand.

Here's what I have so far: https://jsfiddle.net/umx1vpwy/

Any help would be massively appreciated!

Code:

function readImage(file) {

     var reader = new FileReader();
     var image = new Image();

     reader.readAsDataURL(file);
     reader.onload = function(_file) {
       image.src = _file.target.result; // url.createObjectURL(file);
       image.onload = function() {
         var w = this.width,
           h = this.height,
           t = file.type, // ext only: // file.type.split('/')[1],
           n = file.name,
           s = ~~(file.size / 1024) + 'KB';
         $('#uploadPreview').append('<img src="' + this.src + '"> ' + w + 'x' + h + ' ' + s + ' ' + t + ' ' + n + '<br>');
       };
       image.onerror = function() {
         alert('Invalid file type: ' + file.type);
       };
     };

   }
   $("#choose").change(function(e) {
     if (this.disabled) return alert('File upload not supported!');
     var F = this.files;
     if (F && F[0])
       for (var i = 0; i < F.length; i++) readImage(F[i]);
   });
<input type="file" id="choose" multiple="multiple" />
<div id="uploadPreview"></div>

I'd just like to say that browser compatibility shouldn't be an issue as this will just be used as a tool in Chrome or Firefox.


回答1:


This should help:

var el = document.querySelector(YOUR SELECTOR);

function onDragEnter(e) {
    e.stopPropagation();
    e.preventDefault();
}

function onDragOver(e) {
    e.stopPropagation();
    e.preventDefault();
}

function onDragLeave(e) {
    e.stopPropagation();
    e.preventDefault();
}

function onDrop(e) {
    e.stopPropagation();
    e.preventDefault();
    setFiles(e.dataTransfer.files);
    return false;
}

el.addEventListener('dragenter', onDragEnter, false);
el.addEventListener('dragover', onDragOver, false);
el.addEventListener('dragleave', onDragLeave, false);
el.addEventListener('drop', onDrop, false);

function setFiles(files){
    //Here you have your files
}



回答2:


You could use Dropzone JS: http://www.dropzonejs.com/

It does exactly what you want and is very, very customizable, light-weight, and open-source.



来源:https://stackoverflow.com/questions/35157214/drag-and-drop-images-from-desktop-to-browser-instead-of-searching-via-input

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