You can use the javascript FileReader API to display the preview image that is provided from the file input field. This is very useful in the sense that you do not need to use php server and ajax to display the image.
My question though is this:
Is there a limit on the size of the image file used? As if the user were to select a 20 MB image, could filereader handle this? And could the computer memory potentially be maximized?
I am only testing locally on my machine at the moment. I tried to download a BMP file (53 MB!), Which took about 15 seconds to process and display on the page. Other 1 / 2MB files are usually displayed instantly.
This is probably not required, but here is my HTML file: (FYI: this code works well in supported browsers)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Dropzone File Upload</title>
</head>
<body>
<img id="uploadPreview" src="default.png" style="width: 100px; height: 100px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<p id="uploadProgress"> </p>
<script type="text/javascript">
function PreviewImage() {
var avatar_image = document.getElementById("uploadImage");
var avatar_preview = document.getElementById("uploadPreview");
var avatar_progress = document.getElementById("uploadProgress");
if ( window.FileReader ) {
var imgReader = new FileReader();
imgReader.readAsDataURL(avatar_image.files[0]);
imgReader.onloadstart = function(e) {
avatar_progress.innerHTML = "Starting to Load";
}
imgReader.onload = function (imgReaderEvent) {
if (
avatar_image.files[0].type == 'image/jpg' ||
avatar_image.files[0].type == 'image/jpeg' ||
avatar_image.files[0].type == 'image/png' ||
avatar_image.files[0].type == 'image/gif' ||
avatar_image.files[0].type == 'image/bmp'
) {
avatar_preview.src = imgReaderEvent.target.result;
}
else {
avatar_preview.src = 'filetype.png';
}
}
imgReader.onloadend = function(e) {
avatar_progress.innerHTML = "Loaded!";
}
}
else {
document.getElementById("uploadPreview").src = "nosupport.png";
}
};
</script>
</body>
</html>
source
share