javascript - Prévisualiser une image avant qu'elle ne soit téléchargée

Mots clés : javascriptjqueryfile-uploadjavascript

meilleur 5 Réponses javascript - Prévisualiser une image avant qu'elle ne soit téléchargée

vote vote

90

imgInp.onchange = evt => {   const [file] = imgInp.files   if (file) {     blah.src = URL.createObjectURL(file)   } }
<form runat="server">   <input accept="image/*" type='file' id="imgInp" />   <img id="blah" src="#" alt="your image" /> </form>
vote vote

83

<input type="file" accept="image/*" onchange="loadFile(event)">  <img id="output"/>  <script>    var loadFile = function(event) {      var output = document.getElementById('output');      output.src = URL.createObjectURL(event.target.files[0]);      output.onload = function() {        URL.revokeObjectURL(output.src) // free memory      }    };  </script>
<input type="file" accept="image/*" onchange="loadFile(event)">  <img id="output"/>  <script>    var loadFile = function(event) {      var reader = new FileReader();      reader.onload = function(){        var output = document.getElementById('output');        output.src = reader.result;      };      reader.readAsDataURL(event.target.files[0]);    };  </script>
vote vote

78

<img id="blah" alt="your image" width="100" height="100" />    <input type="file"       onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">
blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345 
vote vote

62

function preview() {     frame.src=URL.createObjectURL(event.target.files[0]); }
<form>   <input type="file" onchange="preview()">   <img id="frame" src="" width="100px" height="100px"/> </form>
vote vote

51

<img id="preview"       src=""       alt=""       style="display:none; max-width: 160px; max-height: 120px; border: none;"/>  <div id="preview_ie"></div> 
#preview_ie {   FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale) }   
<script type="text/javascript">   {% include "pic_preview.js" %} </script>   <!--[if gte IE 7]>  <script type="text/javascript">   {% include "pic_preview_ie.js" %} </script> 
function readURL (imgFile) {       var newPreview = document.getElementById('preview_ie');   newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;   newPreview.style.width = '160px';   newPreview.style.height = '120px'; }     

Questions similaires