---
# Image preview

**URL:** https://modul-r.codekraft.it/image-preview/
Date: 2021-07-26
Author: Erik
Post Type: post
Summary: This is an example created some times ago for a support question into contact form 7 support forum, but could be very useful in order to show the uploaded images into a form with a input type file. ref. https://wordpress.org/support/topic/image-upload-preview-before-submit/ Example 2 This is another example that check the image size to be less than […]
Categories: Blog, Contact form 7
---

This is an example created some times ago for a support question into contact form 7 support forum, but could be very useful in order to show the uploaded images into a form with a [input type file.](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file)

ref. [https://wordpress.org/support/topic/image-upload-preview-before-submit/](https://wordpress.org/support/topic/image-upload-preview-before-submit/)

[contact-form-7 id="665" title="image upload"]

```
[file fileuploader filetypes:jpg id:uploader]
<div id="preview"></div>
<script>
var uploader = document.getElementById('uploader');
uploader.addEventListener('change', function(event) {
  var binaryData = [];
  binaryData.push(document.getElementById('uploader').files);
  if (binaryData[0][0]) {
    var img = document.createElement('img');
    img.src = window.URL.createObjectURL(binaryData[0][0]);
    document.getElementById('preview').innerHTML = '';  
    document.getElementById('preview').appendChild(img);
  }
});
var wpcf7Elm = document.querySelector( '.wpcf7' );
wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
  document.getElementById('preview').innerHTML = '';  
}, false );
</script>
[submit "Submit"]
```

##### Example 2

This is another example that check the image size to be less than 5000px, otherwise an error will be shown using the javascript validity alert

[contact-form-7 id="3604" title="image upload 2"]

```
[file fileuploader filetypes:jpg id:uploader]
<div id="preview"></div>
<script>
var _URL = window.URL;
const fileInput = document.getElementById( 'uploader' );
fileInput.onchange = function () {
	let file, img;
	if ( ( file = this.files[ 0 ] ) ) {
		img = new Image();
		img.onload = function () {
			if ( this.width * this.height < 5000 ) {
			        alert( 'image pixels ' + this.width * this.height + '. OK!' );
			} else {
				alert( this.width + ' ' + this.height );
				fileInput.value=null;
				fileInput.setCustomValidity( 'error' );
				fileInput.reportValidity();
			}
		};
		img.onerror = function () {
			alert( 'not a valid file: ' + file.type );
		};
		img.src = _URL.createObjectURL( file );
	}
};
</script>
[submit "Submit"]
```

---

## Categories

- Blog
- Contact form 7

---

## Navigation

- [Modul*R](https://modul-r.codekraft.it/)

---

## Footer Links

- [WordPress](https://wordpress.org/)