我使用下面的代码在上传前预览图片,效果很好。但是如何修复图像扩展,使用户也不会上传任何无效的图像和大小
<html lang="en">
<head>
<title>Change image on select new image from file input</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<input type="file" name="file" id="profile-img">
<img src="" id="profile-img-tag" width="200px" />
<br />
<input type="file" name="file" id="profile-img2">
<img src="" id="profile-img2-tag" width="200px" />
<br />
<input type="file" name="file" id="profile-img3">
<img src="" id="profile-img3-tag" width="200px" />
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#' + $(input).attr('id') + '-tag').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("[type=file]").change(function() {
readURL(this);
});
</script>
</body>
</html>
提前致谢。
最佳答案
<html lang="en">
<head>
<title>Change image on select new image from file input</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
</head>
<style type="text/css">
.image-holder{
height: 200px;
}
.image-holder img{
max-height: 100%;
}
</style>
<body>
<input id="fileUpload_one" type="file" multiple />
<div id="image-holder_one" class="image-holder"></div>
<script type="text/javascript">
$("#fileUpload_one").on('change', function () {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder_one");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
</script>
</body>
</html>
在放置图片的div中添加类,并相应地通过css为图片赋予样式。希望它有帮助我将 css 和类添加到 div 希望它有帮助。
关于javascript - 如何限制除 jpg png 或 gif 之外的图像大小和扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54527795/