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/
[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
[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"]
No comments yet, be the first!