Today I have been attempting to make a thumbnail up loader which uses drag and drop and the file API.
I feel as if i have got reasonably far. But the DataURI that is provided to be the source in my image file ALWAYS returns as [object file] and therefore doesn't show the image.
Any help?!
Thanks. Danny
(below is my code)
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#thumbnailPreview
{
width:149px;
height:137px;
border:3px dashed #333;
border-radius:10px;
text-align:center;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$("document").ready(function() {
if (!!FileReader)
{
$("#thumbnailPreview").append("<p>Drag image here to set as thumbnail</p>")
$("#thumbnailUploadBox").hide();
var thumbnailPreview = document.getElementById("thumbnailPreview")
// init event handlers
thumbnailPreview.addEventListener("dragenter", preventDefault, false);
thumbnailPreview.addEventListener("dragexit", preventDefault, false);
thumbnailPreview.addEventListener("dragover", preventDefault, false);
thumbnailPreview.addEventListener("drop", drop, false)
function preventDefault(evt)
{
evt.stopPropagation();
evt.preventDefault();
}
function drop(evt)
{
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
var noOfFiles = files.length;
if (noOfFiles === 1)
{
handleImages(files);
}
else
{
alert("You appear to be attempting to upload more or less than 1 image. You can only have one thumbnail image. Please try again.");
}
}
function handleImages(files)
{
var file = files[0];
{
if(file.type.indexOf("image") == 0)
{
$("#thumbnailPreview").empty().append('<p>Working on it!</p><progress id="progressbar"></prog开发者_C百科ress>');
var reader = new FileReader();
reader.onloadend = handleReaderLoadEnd;
reader.onprogress = handleReaderProgress;
reader.readAsDataURL(file);
}
else
{
alert("The file you dragged wasn't an image. Please drag another file before attempting to upload");
}
}
}
function handleReaderLoadEnd(e) {
$("#thumbnailPreview").empty().prepend('<img id="thumbnailPreviewImage">');
$("#thumbnailPreviewImage").attr({src: e.target.result});
}
function handleReaderProgress(evt)
{
if (evt.lengthComputable)
{
var loaded = (evt.loaded / evt.total);
$("#progressbar").attr({ value: loaded * 100 });
}
}
}
});
</script>
</head>
<body>
<form action="lighthouseMaker.php" enctype="application/x-www-form-urlencoded" method="post">
<div id="thumbnailPreview">
<p>Upload an Image 149 x 137px</p>
</div>
<div id="thumbnailUploadBox">
<input type="file" name="thumbnail">
</div>
</form>
</body>
</html>
You can use window.URL.createObjectURL / window.URL.revokeObjectURL
to get uri for a file object. It is better than readAsDataURL
.
var img = document.createElement('img');
img.src = (window.URL || window.webkitURL || window.mozURL).createObjectURL(files[0]);
Firefox and Google Chrome support that feature.
精彩评论