i092173
i092173

Reputation: 53

JS Drag and Drop image URL

Hi I'm building a image uploader so I can insert images into my blog articles, I have a form that does all my image uploading then I'm displaying the images in my create an article page via URL saved to the database. What I'm trying to do is build a drag and drop to select the image from the page and ondrop get the url on that image so I can save it to the data base and save the url into my articles table. So what I need is the URL of the image when its dropped in the drop box so ill be able to save the url in the database for in my articles table. Heres my code, thanks for any help in advance!

PHP/HTML

$sql = "SELECT * FROM images";
    $i = 0;

    if($data = query($sql)) {

        while($image = mysqli_fetch_array($data)) {
        ?>
        <div class="layout-column four">
            <img id="drag<?php echo $i++ ?>" src="<?php echo $image['file_name']?>" alt="<?php echo $image['description'] ?>" ondragstart="drag(event)">
        </div>
        <?php

    }

<div id="drop" class="layout-column twelve" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

JAVASCRIPT

function allowDrop(ev)
{
ev.preventDefault();
}

function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}

function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));

var drop = document.getElementById('drop');
document.write(drop);
}

Upvotes: 4

Views: 1795

Answers (2)

Unmitigated
Unmitigated

Reputation: 89472

event.dataTransfer.getData('text/html') can be used to get the HTML of the dropped image. Then, DOMParser can be used to read the source of the image, which works both for images on the page and images dropped from other sites.

Demo:

let dropArea = document.getElementById('dropArea');
dropArea.addEventListener('dragover', e => e.preventDefault());
dropArea.addEventListener('drop', function(e) {
  e.preventDefault();
  let html = e.dataTransfer.getData('text/html');
  let src = new DOMParser().parseFromString(html, "text/html")
              .querySelector('img').src;
  console.log(src);
});
<img src="https://dummyimage.com/100x100/00ff11/000000&text=Drag+Me" draggable>
<div id="dropArea" style="height: 100px; background: dodgerblue; text-align: center;">Drop here</div>

Upvotes: 0

laaposto
laaposto

Reputation: 12213

Try this:

function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault(); 
    var imageUrl = evt.dataTransfer.getData('text/html');

    var rex = /src="?([^"\s]+)"?\s*/;
    var url, res;

    url = rex.exec(imageUrl);
    alert(url[1]);
}

DEMO

Upvotes: 2

Related Questions