[英]How to limit the file upload while uploading folder
我允許用戶上傳文件夾如下
<input type="file" (change)="onFileChanged($event)" webkitdirectory directory multiple/>
它按預期工作。 但我想將總大小限制為小於 20 MB。 我怎樣才能做到這一點
onFileChanged(event): void {
const allFiles = event.target.files;
console.log(allFiles);
}
有沒有直接的方法可以做到這一點,或者我需要遍歷每個文件並計算總大小並檢查它是否超過?
是的,從文件輸入中,您需要遍歷其所有.files
條目:
inp.onchange = e => { const total_size = [...inp.files].reduce( (sum, file) => (sum + file.size), 0 ); console.log( "total size", total_size.toLocaleString( "en-US" ), "b" ); };
<input type="file" id="inp" webkitdirectory>
event.target.files
將返回FileList 。 然后你可以使用Array.from
並使用reduce
來獲取每個文件的大小。 這是在 javascript 和 html 中。 同樣可以在 angular 中完成
function fileUpload(e) { const sz = Array.from(e.target.files).reduce((acc, curr) => { return acc += curr.size; }, 0) console.log(sz) }
<input type="file" multiple onchange='fileUpload(event)'>
您可以獲得文件的整體大小並阻止上傳:
onFileChanged(event): void {
const overallSize = event.target.files
.reduce((a, c) => {return (c.size / 1024 / 1024) + a }, 0);
if (overallSize > 1) // 1 Mb
alert('File size exceeds 1 MB');
else {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.