我上传照片时出错,照片名称显示,但图片没有显示。我不知道为什么会出现错误——脚本在正文的末尾。
浏览器中的错误消息
new:181 Uncaught TypeError: Cannot read property '0' of undefined
at HTMLInputElement.<anonymous> (new:181)
at HTMLInputElement.dispatch (jquery.min.js:2)
at HTMLInputElement.v.handle (jquery.min.js:2)
HTML代码
<div class="form-group row">
<label class="col-sm-4 col-form-label">Photos:</label>
<div class="col-sm-8">
<input type="file" id="fileImage" accept="image/png, image/jpeg"
class="mb-2"/>
<img id="thumbnail" alt="Photos preview" th:src="@{/images/default-user.png}"
class="img-fluid"/>
</div>
</div>
JQuery代码
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#buttonCancel").on("click", function () {
window.location = "[[@{/users}]]";
});
$("#fileImage").change(function () {
fileSize = this.file[0].size;
alert("File size: " + fileSize);
// max 1MB
if (fileSize > 1048576) {
this.setCustomValidity("You must choose an image less than 1MB");
this.reportValidity();
} else {
this.setCustomValidity("");
showImageThumbnail(this);
}
});
});
function showImageThumbnail(fileInput) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function (e) {
$("#thumbnail").attr("src", e.target.result);
};
reader.readAsDataURL(file);
}
</script>
这里有两件事:您忘记声明fileSize变量。这是
this.files[0]
以下是获取文件大小的方法
let fileSize = this.files[0].size;
以及的一个工作示例
$(document).ready(function () {
console.log('test')
$("#buttonCancel").on("click", function () {
window.location = "[[@{/users}]]";
});
$("#fileImage").change(function () {
let fileSize = this.files[0].size;
alert("File size: " + fileSize);
// max 1MB
if (fileSize > 1048576) {
this.setCustomValidity("You must choose an image less than 1MB");
this.reportValidity();
} else {
this.setCustomValidity("");
showImageThumbnail(this);
}
});
});
function showImageThumbnail(fileInput) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function (e) {
$("#thumbnail").attr("src", e.target.result);
};
reader.readAsDataURL(file);
}