Completing this task involves multiple steps that can be executed in various ways.
Here is a basic solution outline utilizing jQuery.
Prevent Default Browser Behavior
Many browsers automatically replace the current window/tab URL with the content's URL being dragged, causing page refresh. To prevent this behavior, the initial step is to intercept these events.
window.addEventListener("dragover",function(e){
e = e || event;
e.preventDefault();
},false);
window.addEventListener("drop",function(e){
e = e || event;
e.preventDefault();
},false);
Retrieve Image URL
Create an img
element without a src
, along with a dropzone area, and begin listening for drop
events on the dropzone. When an image is dropped, extract its URL using DataTransfer
. Update the src
of the empty img
with the retrieved URL.
$('#dropzone').on('drop', function(e) {
var url = e.originalEvent.dataTransfer.getData('url');
$('#result').attr("src",url);
});
Save Image
Automating image saving via Javascript poses challenges, but workarounds like FileSaver.js exist. Using FileSaver.js requires converting the img
to a blob or canvas object first, as explained here.
EXAMPLE (no saving)
window.addEventListener("dragover", function(e) {
e = e || event;
e.preventDefault();
}, false);
window.addEventListener("drop", function(e) {
e = e || event;
e.preventDefault();
}, false);
$('#dropzone')
.on('drop', function(e) {
e.stopPropagation();
e.preventDefault();
var url = e.originalEvent.dataTransfer.getData('url');
$('#result').attr("src", url);
});
#dropzone {
width: 100px;
height: 100px;
border: 1px solid black;
margin: 10px;
}
#result {
margin: 10px;
max-width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dropzone">Drop Here</div>
<img id="result" />