我有一个用于类(class)项目的假个人资料系统,它需要一张个人资料图片,并且需要一个选项来在本地(从您的硬盘驱动器)更改它。我有一个有效的 img
标签,它默认包含一个占位符图像,当您单击 change picture
时,将打开一个打开的文件对话框。我现在需要做的就是使用他们选择的图像为 img
标签设置图像链接。这是我目前所拥有的。
<div id="userphoto">
<a><div class="gravatar-wrapper-128"><img id="image" src="http://blog.ramboll.com/fehmarnbelt/wp-content/themes/ramboll2/images/profile-img.jpg" alt="" class="logo" width="120" height="120"></div></a>
<div class="change-picture-slide" style="top: 30px;">
<input accept="image/*" type="file" id="upload" name="upload" style="visibility: hidden; width: 1px; height: 1px" />
<a href="" onclick="changePicture(); return false">Change Picture</a>
</div>
</div>
<script>
function changePicture() {
//open the open file dialog
document.getElementById('upload').click();
var link = document.getElementById('upload').url;
//change picture
var img = document.getElementById("image");
img.src = link;
}
</script>
知道这是不可能的,我怎么能让用户选择的图像匿名上传到imgur并使用此链接?
最佳答案
您可以使用 javascript 中的文件阅读器来尝试。
<div id="userphoto">
<div class="gravatar-wrapper-128"><img id="image" src="body-img.jpg" alt="" class="logo" width="120" height="120"></div>
<div class="change-picture-slide" style="top: 30px;">
<input accept="image/*" type="file" id="upload" name="upload" onchange="readURL(this);"style="visibility: hidden;" />
<a href="" onclick="changePicture(); return false">Change Picture</a>
</div>
</div>
<script>
function changePicture(){
$('#upload').click();
}
function readURL(input)
{
if (input.files && input.files[0])
{
var reader = new FileReader();
reader.onload = function (e)
{
$('#image')
.attr('src',e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
关于JavaScript 选择图像到 img 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24579754/