Due modi di gestire la cosa.
codice:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>test</title> <style> #preview { width: 300px; height: 300px; border: 1px solid black; } #preview>img { width: inherit; height: inherit; } </style> </head> <body> <div id="preview"> <img src="#" alt="preview"> </div> <label for="photo">API FileReader()</label> <input type="file" name="photo" accept="image/*" id="photo"> <br> <label for="photo2">URL.createObjectURL()</label> <input type="file" name="photo2" accept="image/*" id="photo2"> <script> const selectPhoto = document.getElementById('photo') const selectPhoto2 = document.getElementById('photo2') const previewImg = document.querySelector('#preview>img') // API FileReader() // - Tramite il metodo readAsDataURL() viene creata in modo asincrono un // dato con codifica a base64, che in questo caso rappresenta l'immagine (dall'input). // Tramite la proprietà "onload" possiamo gestire il dato da passare al tag html image.src // - Gestisce automanticamente la memoria tramite garbage collector selectPhoto.addEventListener('change', (e) => { const reader = new FileReader() reader.readAsDataURL(e.target.files[0]) reader.onload = () => { previewImg.src = reader.result } }) // URL.createObjectURL() // - Creata in modo sincrono un hash per la rappresentazione dell'immagine // - Necessità del metodo revokeObjectURL() per ripulire la memoria selectPhoto2.addEventListener('change', (e) => { const url = URL.createObjectURL(e.target.files[0]) previewImg.src = url URL.revokeObjectURL(url) }) </script> </body> </html>

Rispondi quotando
