我想准备一张个人资料图片上传表格。这里有什么必要?能够在提交之前查看图像如何适合,这是我不幸陷入困境的那一刻。我在此处附加了我的 JSP 和 JS 文件中的表单元素,该元素应该处理通过 formData 检索表单文件。由于某种原因,JS 不愿意对 backgroundImage 属性做任何事情,也不会引发任何类型的错误。我真的很想为这项任务提供一些帮助。只使用简单的语言,因为我是一个极端主义者;)。
HTML:
<div class="profilePicture">
<form class="choosePhotoLabel" enctype="multipart/form-data" action="savePictureServlet" method="post">
<input class="choosePhoto" type="file" name="picture">
<input class="photoOk" type="submit" value="this is the picture!">
</form>
</div>
JavaScript:
document.addEventListener("DOMContentLoaded", function () {
let formInHTML = document.getElementsByClassName("choosePhotoLabel").item(0);
let formInputInHTML = document.getElementsByClassName("choosePhoto").item(0);
let imagePlace = document.getElementsByClassName("profilePicture").item(0);
let pictureReader = new FileReader();
function mlemToFile(mlem) {
mlem.lastModifiedDate = new Date();
mlem.name = "nonMlemPicture";
return mlem;
}
formInputInHTML.addEventListener("change", function () {
let formData = new FormData(formInHTML);
let formPicture = formData.get("picture");
if (formPicture != null) {
let nonMlemPicture = mlemToFile(formPicture);
pictureReader.readAsDataURL(nonMlemPicture);
if (pictureReader.result != null) {
let picture64 = pictureReader.result.replace(/^data:.+;base64,/, '');
imagePlace.style.backgroundImage = picture64;
}
}
});
});