在网页上,我显示他们分配的用户个人资料图片。在此之下,我有一个文件输入,允许用户选择新的个人资料图片。我想在网页上当前个人资料图片所在的位置显示新的个人资料图片。
为此,我需要更改 <img>
的 src显示用户当前个人资料图片的标签。我需要更改 src
img
的属性到用户想要更改个人资料图片时选择的任何文件。
我已经编写了一些代码,但它根本不起作用。
这是我的HTML:
// Profile picture I display in browser <img style="position: relative; left: 60px; top: 25px;" width="55px" src="{{ user.profilePic.url }}" alt="">
<label id="profilePhoto_update" for="profilepic_update">Change Profile Photo</label>
JS:
img = $("#profilePhoto_update")
$("#profilePhoto_update").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("#profilePhoto_update").after(img);
}
});
有人知道如何实现这个功能吗?谢谢。
最佳答案
您正在将事件绑定(bind)到 <label>
而不是 <input>
.
此外,我建议使用 Object URLs而不是数据 URL。
这是一个固定的示例:
img = $("#profilePhotoImg")
$("#profilePhotoInput").change(function(e) {
var url = URL.createObjectURL(e.target.files[0])
img.attr('src', url)
});
希望这会有所帮助!
关于javascript - JS - 在浏览器中查看选定的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60802005/