将上传的图片永久替换为占位符图片

Replace uploaded image with placeholder image permanently

本文关键字:替换 占位符      更新时间:2023-09-26

我一直在尝试提供用我上传的占位符图像替换图像的功能,这样我的客户就不需要在(任何CMS)的后端登录,而且几乎所有客户都是非技术人员。

下面的代码段将显示占位符图像以及"上传文件按钮"。一旦他们上传了他们的图像,我将删除选择文件选项。是否有可能将他们上传的图像存储在网站文件夹中的某个地方?

.HTML:

<input type='button' id='remove' value='remove' class='hide'/>
<input type='file' id="imgInp" /><br>
<img width="230px" id="blah" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png" alt="your image" />

.JS:

$('#blah').show();
$('#remove').hide();  
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    $("#imgInp").change(function(){
        if( $('#imgInp').val()!=""){
            $('#remove').show();
            $('#blah').show('slow');
      }
        else    {
                     $('#remove').hide();
        $('#blah').hide('slow');
        }
        readURL(this);
    });

    $('#remove').click(function(){
          $('#imgInp').val('');
          $(this).hide();
          $('#blah').hide('slow');
 $('#blah').attr('src','http://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png');
});

在这里查看 JSFIDDLE

尝试使用它

<input id="src" type="file"/>
<input type="button" id="rem" value="remove" style="visibility:hidden;" onclick="myfun()">
<img id="target" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png" style="width:100px;height:100px;"/> 
<script>
function showImage(src,target) {
var fr=new FileReader();
fr.onload = function(e) { target.src = this.result; };
src.addEventListener("change",function() {
fr.readAsDataURL(src.files[0]);
document.getElementById("src").style.visibility = "hidden";
document.getElementById("rem").style.visibility = "visible";
});
}
var src = document.getElementById("src");
var target = document.getElementById("target");
showImage(src,target);
function myfun(){
target.src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png";
document.getElementById("src").style.visibility = "visible";
document.getElementById("rem").style.visibility = "hidden";
};
</script>