Pregunta

I want drop jpg to Browser from local, and display it on Browser.

I write code, but it don't display jpg.

Please advice.

html

<img id="img1" ondragover="doDragOver(event);"
               ondrop="doDrop(event);" 
               class="droppable">

css

.droppable {
        width:500px;
        height:500px;
        background-color: gray;
}

script

function doDragOver(event){
    var type = event.dataTransfer.types.contains("Files");
    if (type){
        event.preventDefault();
    }
}

function doDrop(event){
    var img = document.getElementById("img1");
    var file = event.dataTransfer.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function() {
        img.src = reader.result;
    }
}
¿Fue útil?

Solución

The problem is that the dragOver function the type list is empty (to it's empty in some browsers), but why check it content? You can check it in the drop function.

Be sure to cancel the default browser behavior using event.preventDefault(); and return false

Code:

function doDragOver(event) {
    event.preventDefault();
    return false
}

function doDrop(event) {
    event.preventDefault();
    var img = document.getElementById("img1");
    var file = event.dataTransfer.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        img.src = reader.result;
    }
}

Demo: http://jsfiddle.net/IrvinDominin/Up2NF/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top