上传前获取文件大小,图像宽度和高度

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

回答:

带有信息数据预览的多张图像上传

使用

使用URL API的示例

图片来源将是代表Blob对象的URL

<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>

使用FileReader API的示例

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

<img src="data:image/png;base64,iVBORw0KGg... ...lF/++TkSuQmCC=">

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>

以上是 上传前获取文件大小,图像宽度和高度 的全部内容, 来源链接: utcz.com/qa/409417.html

回到顶部