0

I want to drag an image from browser and drop it inside an object and get the dropped file simply like this:

$('#image-upload-preview').on('drop', drop);

function drop(e) {
  const file = e.originalEvent.dataTransfer;
  console.log('file', file[0]); // this brings undefined
  //console.log('file', file); // this bring empty file list
}

window.addEventListener("dragover", (e) => {
  e = e || event;
  e.preventDefault();
}, false);

window.addEventListener("drop", (e) => {
  e = e || event;
  e.preventDefault();
}, false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image_container">
  <img id="image-upload-preview" style="width:100%" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSClDjLZzrjD5FHPX-nNU5QoTWK-C2XcOD-M6Aabozw6Oem8-0ejje8Lk5DmNbhVOvvMfc&usqp=CAU">
  <div id="cropped_result"></div>
</div>

But the file returns empty file list???

How can I fix this?

Sara Ree
  • 3,417
  • 12
  • 48

1 Answers1

1

You dont get list of files because your const is not correct.

You need to put .files : e.originalEvent.dataTransfer.const.files

$('#image-upload-preview').on('drop', drop);

function drop(e) {
  e.stopPropagation();
  e.preventDefault();

  var file = e.originalEvent.dataTransfer.files;
  var fd = new FormData();

  console.log(file[0]);

  fd.append('file', file[0]);
  
  // process upload with ajax
}

window.addEventListener("dragover", (e) => {
  e = e || event;
  e.preventDefault();
}, false);

window.addEventListener("drop", (e) => {
  e = e || event;
  e.preventDefault();
}, false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image_container">
  <img id="image-upload-preview" style="width:100%" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSClDjLZzrjD5FHPX-nNU5QoTWK-C2XcOD-M6Aabozw6Oem8-0ejje8Lk5DmNbhVOvvMfc&usqp=CAU">
  <div id="cropped_result"></div>
</div>
SKJ
  • 2,184
  • 1
  • 13
  • 25
  • Drag and drop an image from browser and you get undefined again...Do you want to know Why? – Sara Ree Oct 22 '21 at 18:45
  • Im using Firefox and it work with drag and drop image @SaraRee I tried with Chrome and it also work. – SKJ Oct 23 '21 at 22:10
  • Drag an image opened from another chrome tab and try to drop it .... the code only works when you drop an image from your computer not from open tab of the browser... pleasev confirm this.. – Sara Ree Oct 24 '21 at 07:36
  • Check this post : https://stackoverflow.com/questions/12954529/jquery-html5-file-drag-and-drop/15809374 – SKJ Oct 24 '21 at 14:07