本文介绍了上传前获取文件大小,图像宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用jQuery或JavaScript上传到我的网站之前,如何获取文件的大小,图像的高度和宽度?

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

推荐答案

使用信息数据预览上传多张图片

使用 HTML5和文件API

Multiple images upload with info data preview

Using HTML5 and the File API

图片来源将是代表Blob对象的URL
<img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">

The images sources will be a URL representing the Blob object
<img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">

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}<br>`);

  const img = new Image();
  img.addEventListener('load', () => {
    EL_preview.appendChild(img);
    EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB<div>`);
    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; }
<input id="browse" type="file" multiple>
<div id="preview"></div>

如果您需要图像源作为长Base64编码的数据字符串

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', `<div>Unsupported format ${file.type}: ${file.name}</div>`);

  const reader = new FileReader();
  reader.addEventListener('load', () => {
    const img  = new Image();
    img.addEventListener('load', () => {
      EL_preview.appendChild(img);
      EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB</div>`);
    });
    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; }
<input id="browse" type="file"  multiple>
<div id="preview"></div>
  

这篇关于上传前获取文件大小,图像宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:44