You can use javascript FileReader API to display a preview of an image which is provided from a file input field. This comes in very useful in the sense that you don't have to use server side php and ajax to display the image.
My question though is this:
Is there any limit to the size of the image file being used? Like if a user was to select an image that is 20MB, would the filereader be able to handle it? And would the machines memory potentially become max-ed out?
I'm testing just locally on my machine at the moment. I attempted to load a bmp file (53MB!), which took about 15 seconds to process and display on the page. Other files at 1/2MB generally display instantaneously.
It's 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 ) { //if supports filereader
var imgReader = new FileReader();
imgReader.readAsDataURL(avatar_image.files[0]); //read from file input
imgReader.onloadstart = function(e) {
avatar_progress.innerHTML = "Starting to Load";
}
imgReader.onload = function (imgReaderEvent) {
//if file is image
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!";
}
}
/* For no support, use ActiveX instead */
else {
document.getElementById("uploadPreview").src = "nosupport.png";
}
};
</script>
</body>
</html>
It seems in Chrome 45 the limit is 261 MB.
Unfortunately there is no error (FileReader.error == null
) when the size is above that limit, the result is just an empty string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With