问题
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