Get file size, image width and height before upload

前端 未结 7 1252
自闭症患者
自闭症患者 2020-11-22 03:50

How can I get the file size, image height and width before upload to my website, with jQuery or JavaScript?

7条回答
  •  后悔当初
    2020-11-22 04:32

    Multiple images upload with info data preview

    Using HTML5 and the File API

    Example using URL API

    The images sources will be a URL representing the Blob object

    const EL_browse  = document.getElementById('browse');
    const EL_preview = document.getElementById('preview');
    
    const readImage  = file => {
      if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )
        return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}
    `); const img = new Image(); img.addEventListener('load', () => { EL_preview.appendChild(img); EL_preview.insertAdjacentHTML('beforeend', `
    ${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB
    `); window.URL.revokeObjectURL(img.src); // Free some memory }); img.src = window.URL.createObjectURL(file); } EL_browse.addEventListener('change', ev => { EL_preview.innerHTML = ''; // Remove old images and data const files = ev.target.files; if (!files || !files[0]) return alert('File upload not supported'); [...files].forEach( readImage ); });
    #preview img { max-height: 100px; }
    
    

    Example using FileReader API

    In case you need images sources as long Base64 encoded data strings

    const EL_browse  = document.getElementById('browse');
    const EL_preview = document.getElementById('preview');
    
    const readImage = file => {
      if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )
        return EL_preview.insertAdjacentHTML('beforeend', `
    Unsupported format ${file.type}: ${file.name}
    `); const reader = new FileReader(); reader.addEventListener('load', () => { const img = new Image(); img.addEventListener('load', () => { EL_preview.appendChild(img); EL_preview.insertAdjacentHTML('beforeend', `
    ${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB
    `); }); img.src = reader.result; }); reader.readAsDataURL(file); }; EL_browse.addEventListener('change', ev => { EL_preview.innerHTML = ''; // Clear Preview const files = ev.target.files; if (!files || !files[0]) return alert('File upload not supported'); [...files].forEach( readImage ); });
    #preview img { max-height: 100px; }
    
    

提交回复
热议问题