我正在使用以下代码上传个人资料图像,并且效果很好,但是问题是,当我上传图片时,它不会像应该的那样显示在边框中!有什么想法为什么会这样?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>form practice</title>
<!--Calculate age from dob script-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#dob").change(function(){
var value = $("#dob").val();
var dob = new Date(value);
var today = new Date();
var age = Math.floor((today-dob) / (365.25 * 24 * 60 * 60 * 1000));
if(isNaN(age)) {
// will set 0 when value will be NaN
age=0;
}
else{
age=age;
}
$('#age').val(age);
});
});
</script>
<!--End of Calculate age from dob script-->
<!--Upload Picture Script-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('input[type=file]').change(function () {
$('#dummyImg').attr('src',URL.createObjectURL(event.target.files[0]));
});
</script>
<!--End of Upload Picture Script-->
<style>
#dummyImg{width:100%;}
.img-block{border:2px solid cyan;
width:200px; padding: 100px;}
</style>
</head>
<body>
<div class="form2" id="form2" name="form2">
<form action="php/form2.php" method="post" id="Personalinfo">
<label for="fname">Name:</label>
<input type="text" id="fname" name="firstname" placeholder="Client Name..">
<label for="lname">Lastname:</label>
<input type="text" id="lname" name="lastname" placeholder="Client Lastname..">
<label for="dob">Birthday:</label>
<input type="text" id="dob" name="dob" placeholder="yyyy/mm/dd..">
<label for="age">Age:</label>
<input type="text" id="age" name="age" placeholder="Client Age.."><br><br>
<div class="img-block">
<img src="dummyImg.png" id="dummyImg" />
</div>
<label for="profilepic">Profile Picture:</label>
<input type="file" id="profilepic" name="profilepic" accept="image/*" placeholder="Profile Pic.." border="5"><br><br>
<input type="submit" name="submitForm2" value="Submit">
</form>
</div>
</body>
</html>
当我在localhost上运行此代码时,上传过程可以正常进行,但是问题是上传的照片没有显示在边框中,应该是正确的!
由于我是编码新手,因此有关如何解决此问题的任何想法都将非常有用。
提前致谢!
最佳答案
这应该工作,这是小提琴https://jsfiddle.net/s4z7fof8/
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#dummyImg').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(function() {
$("input:file").change(function (){
console.log("File selected");
readURL(this);
});
});
</script>
关于javascript - 图像未显示在边框中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45522690/