ReadAsDataURL() doesn't work

元气小坏坏 提交于 2019-12-13 00:26:38

问题


I was trying to implement a Drag n' Drop feature in my website. I need to convert the dropped image into Data URI so I can use it with JCrop and upload it after.

            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;
            }

But nothing shows up in the console. Not even undefined. The files variable returns an Object FileList with the image I dropped, so the problem is not there. How can I fix this? :(


回答1:


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

solution:

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



回答2:


You can try this

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);
}


来源:https://stackoverflow.com/questions/19740523/readasdataurl-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!