2013-11-02 4 views
1

Я пытался реализовать функцию Drag n 'Drop на своем веб-сайте. Мне нужно преобразовать отброшенное изображение в URI данных, чтобы я мог использовать его с JCrop и загружать его после.ReadAsDataURL() не работает

  drop: function (e) { 
       e = e || window.event; 
       e.preventDefault(); 
       e = e.originalEvent || e;   
       var files = (e.files || e.dataTransfer.files); 
       var reader = new FileReader(); 
       reader.onload = function (event){ 
        console.log(event.target.result); 
       }; 
       reader.readAsDataURL(files); 
       return false; 
      } 

Но ничего не отображается в консоли. Даже не undefined. Переменная files возвращает Object FileList с уменьшенным изображением, поэтому проблемы там нет. Как я могу это исправить? :(

+0

Вы можете создать скрипку с проблемой? – Ronny

ответ

2
//applies to only one file. 
reader.readAsDataURL(files); 

решение:

for(var i=0;i<files.length;i++){ 
    reader.readAsDataURL(files[i]); 
} 
+0

СПАСИБО ВАМ ОЧЕНЬ, это работает, когда я заменяю цитату в полуточку :) – Erman

+0

это был всего лишь макияж. не за что) – Romko

0

Вы можете попробовать это

HTML

<div id="dropBox"> 
<div>Drop your image here...</div> 
</div> 

CSS

#dropBox { 
    margin: 15px; 
    width: 300px; 
    height: 300px; 
    border: 5px dashed gray; 
    border-radius: 8px; 
    background: lightyellow; 
    background-size: 100%; 
    background-repeat: no-repeat; 
    text-align: center; 
    } 

#dropBox div { 
    margin: 100px 70px; 
    color: orange; 
    font-size: 25px; 
    font-family: Verdana, Arial, sans-serif; 
    } 

JavaScript

var dropBox ; 

window.onload = function() 
{ 
dropBox = document.getElementById("dropBox"); 
dropBox.ondrop = drop; 
}; 

function drop(e) 
{ 
    // Get the dragged-in files. 
    var data = e.dataTransfer; 
    var files = data.files; 

// Pass them to the file-processing function. 
    processFiles(files); 
} 

function processFiles(files) 
{ 
    var file = files[0]; 

// Create the FileReader. 
var reader = new FileReader(); 

// Tell it what to do when the data URL is ready. 
    reader.onload = function (e) 
    { 
    // Use the image URL to paint the drop box background 
    dropBox.style.backgroundImage = "url('" + e.target.result + "')"; 
    }; 

// Start reading the image. 
reader.readAsDataURL(file); 
} 
Смежные вопросы