我希望有input
代码用于上传多张图片。
我在预览中有格式限制(在更改触发器上调用),如下所示。如何为大于100kb的图像添加另一个限制?
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);
});
}
}
答案 0 :(得分:2)
您可以在输入file.size
事件中使用change
来获取字节大小。基于此,您可以提供有关文件大小的警报:
if(file.size > 100000){
return alert("file is to big")
}
<强>演示强>
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)">
答案 1 :(得分:0)
在输入标记中添加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调用函数:在提交按钮上将执行此函数。它将获取Input标记的max-size属性值,并将其与Files size值进行比较。
$(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;
}
});
});
答案 2 :(得分:0)
使用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);
});
}
}
答案 3 :(得分:0)
使用以下方法并在提交输入表单或文件输入控件更改时调用
function ValidateImageFile() {
var file = $(".fupFileUpload")[0].files[0]; //fupFileUpload add class to your file upload control
var fileType = file.type;
var ValidImageTypes = ["image/gif", "image/jpeg", "image/png", "image/tiff", , "image/bmp"];
if ($.inArray(fileType, ValidImageTypes) < 0) {
alert("Please select valid image file."); //set label text if you want to display error message in label
return false;
}
else if( file.size > 1000000){ // file.size is in bytes
alert("Please select file less than 100 kb.");
return false;
}
return true;
}