我想有input标签上传多个图片。
我在预览中有格式限制(调用更改触发器)如下所示。如何对大于100 can的图像添加另一个限制?
function previewPhotoInput() {
var $preview = $('#previewPhoto');
if (this.files) {
var files = this.files;
$.each(files, function (i, file) {
if (!/\.(jpeg|jpg)$/i.test(file.name)) {
return alert("Invalid Format!");
}
var reader = new FileReader();
$(reader).on("load", function () {
$preview.append($("<img/>", { src: this.result, height: 100 }));
});
reader.readAsDataURL(file);
});
}
}发布于 2017-11-08 06:31:40
使用file.size。您将按字节大小,但可以转换为KB。
function previewPhotoInput() {
var $preview = $('#previewPhoto');
if (this.files) {
var files = this.files;
$.each(files, function (i, file) {
var size=(file.size)/1000;
if(size>100){
return alert("File should be less than 100K");
}
if (!/\.(jpeg|jpg)$/i.test(file.name)) {
return alert("Invalid Format!");
}
var reader = new FileReader();
$(reader).on("load", function () {
$preview.append($("<img/>", { src: this.result, height: 100 }));
});
reader.readAsDataURL(file);
});
}
}发布于 2017-11-08 06:28:10
您可以在输入file.size事件上使用change获取大小(以字节为单位)。基于此,您可以提供有关文件大小的警报:
if(file.size > 100000){
return alert("file is to big")
}Demo
function previewPhotoInput(obj) {
var $preview = $('#previewPhoto');
if (obj.files) {
var files = obj.files;
$.each(files, function(i, file) {
if (!/\.(jpeg|jpg)$/i.test(file.name)) {
return alert("Invalid Format!");
}
if(file.size > 100000){
return alert("file is to big")
}
var reader = new FileReader();
$(reader).on("load", function() {
$preview.append($("<img/>", {
src: this.result,
height: 100
}));
});
reader.readAsDataURL(file);
});
}
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple onchange="previewPhotoInput(this)">
发布于 2017-11-08 06:27:57
在输入标签中添加data-max-size="100“
<form class="upload-form">
<input id="previewPhoto" class="upload-file" data-max-size="100" type="file" >
<input type=submit>
</form>Jquery调用函数:在submit按钮上,将执行此函数。它将获得输入标签的最大大小属性值,并将其与文件大小值进行比较。
$(function(){
var fileInput = $('#previewPhoto');
var maxSize = fileInput.data('max-size');
$('#previewPhoto').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 then' + maxSize + ' bytes');
return false;
}else{
alert('file size is correct- '+fileSize+' bytes');
}
}else{
alert('choose file, please');
return false;
}
});
});https://stackoverflow.com/questions/47172888
复制相似问题