如何将图片上传大小限制在2mb以下?

时间:2022-11-15 01:51:36

I have an html select option for uploading images.

我有一个用于上传图像的html选项。

<div class="row smallMargin"><div class="col-sm-6">  Attach Image</div><div class="col-sm-6">  <input type="file" ng-model="image" accept="image/*"></div></div>

How can I restrict the user from uploading images which are larger than 2MB?

如何限制用户上传大于2MB的图像?

1 个解决方案

#1


5  

This example should give you an idea of how to do it:

这个例子可以让你知道如何做到这一点:

HTML

<form  class="upload-form">    <input class="upload-file" data-max-size="2048" type="file" >    <input type=submit></form>

JS

$(function(){    var fileInput = $('.upload-file');    var maxSize = fileInput.data('max-size');    $('.upload-form').submit(function(e){        if(fileInput.get(0).files.length){            var fileSize = fileInput.get(0).files[0].size; // in bytes            if(fileSize>maxSize){                alert('file size is more than ' + maxSize + ' bytes');                return false;            }else{                alert('file size is correct - '+fileSize+' bytes');            }        }else{            alert('Please select the file to upload');            return false;        }    });});

#1


5  

This example should give you an idea of how to do it:

这个例子可以让你知道如何做到这一点:

HTML

<form  class="upload-form">    <input class="upload-file" data-max-size="2048" type="file" >    <input type=submit></form>

JS

$(function(){    var fileInput = $('.upload-file');    var maxSize = fileInput.data('max-size');    $('.upload-form').submit(function(e){        if(fileInput.get(0).files.length){            var fileSize = fileInput.get(0).files[0].size; // in bytes            if(fileSize>maxSize){                alert('file size is more than ' + maxSize + ' bytes');                return false;            }else{                alert('file size is correct - '+fileSize+' bytes');            }        }else{            alert('Please select the file to upload');            return false;        }    });});