I have a form which allows the user to upload a picture. After the user has submitted the form, I'd like to generate on the front-end a thumbnail for each picture and then store it on server.
For security reason it's not possible to alter the value of a file input field, so how could I send to server some thumbnails images generated on the front-end in js?
Is it possible on front-end to generate a thumbnail from the image set in the input file field before form submit? And then submitting both at same time?
To add a new thumbnail image for a selected file, first click the Add button as shown below in the image. 2. A new window will then appear and show a list that will let you select up to three files at once. Click Select File to select the image file you wish to assign as the thumbnail image file.
Use the border property to create thumbnail images. Wrap an anchor around the image to use it as a link. Hover over the image and click on it to see the effect.
I found This simpler yet powerful tutorial. It simply creates an img
element and, using the fileReader object, assigns its source attribute as the value of the form input
function previewFile() { var preview = document.querySelector('img'); var file = document.querySelector('input[type=file]').files[0]; var reader = new FileReader(); reader.onloadend = function () { preview.src = reader.result; } if (file) { reader.readAsDataURL(file); } else { preview.src = ""; } }
<input type="file" onchange="previewFile()"><br> <img src="" height="200" alt="Image preview...">
After a better search online I found the answer to my question.
It is possible to combine canvas together with the File API.
Try to upload any picture in the demo below and see that a new generated thumbnail will appear on the right side of the form.
DEMO: http://jsfiddle.net/a_incarnati/fua75hpv/
function handleImage(e){ var reader = new FileReader(); reader.onload = function(event){ var img = new Image(); img.onload = function(){ canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img,0,0); } img.src = event.target.result; } reader.readAsDataURL(e.target.files[0]); }
A good answer has been given by DerekR to this question:
How to upload image into HTML5 canvas
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