Rails jQuery Drag and Drop Show Image

Drag and Drop

Use drag and drop event handler of jQuery.
To show image, we also need FileReader API.
Implement feature using jQuery and coffeescript

View

.html.erb

<div id="draggable">
<%= image_tag 'blankimage.png' %>
</div>

This is temporary image.

JavaScript(CoffeeScript)

$ ->
  el = $("#draggable");
  el.on 'drop', (e) ->  
    e.preventDefault()
    console.log("File")
    files = e.originalEvent.dataTransfer.files
    reader = new FileReader()
    file = files[0]
    reader.onload = (e) ->
      dataurl = e.target.result
      $(el).find('img').attr('src', dataurl)
      return
    reader.readAsDataURL(file)  
    return
  return

$(document).on 'dragover', (e) ->
  e.stopPropagation()
  e.preventDefault()
  return
  
$(document).on 'drop', (e) ->
  e.stopPropagation()
  e.preventDefault()
  console.log("Document")
  return

To prevent browser drag and drop feature(show image in browser), we need to prevent default events dragover and drop.

And get file object and create FileReader object and read file
Finally, set source into a target element.