显示图像预览而不是文本

17 javascript

我们正在尝试将图片上传到我们的网站.

  1. 我们点击" 上传图片 "按钮.

在此输入图像描述

  1. 然后它会显示弹出框.

在此输入图像描述

  1. 然后我们点击上传新图片按钮

  2. 之后,我们将从计算机中选择图像并显示上传的图像

在此输入图像描述

而不是消息"图像上传",我想显示上传图像的预览,就像这个Jsfiddle

代码显示消息"图像已上传"

<input type="file" id="add_image_{{rand}}" class="newcustomimage" name="new_image" value=""/>
Run Code Online (Sandbox Code Playgroud)

JS

jQuery(document).ready(function () {
    jQuery('body').delegate('.newcustomimage', 'change', function () {
        if(jQuery(this).val()) {
            jQuery(this).parent().parent().append('<div id="add_image_2508269_success" class="success-message validation-advice"> Image Uploaded.</div>');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我对以上代码进行了以下更改,以显示" 图像预览 "而不是消息.现在我们上传图片后没有显示图片预览.相反,它在我们在网站上传图像之前显示如下图像.

在此输入图像描述

<input type="file" id="add_image_{{rand}}" class="newcustomimage" name="new_image" value=""/>
<img id="blah" src="http://example.com/media/custom_product_preview/quote" />
Run Code Online (Sandbox Code Playgroud)

JS

jQuery(document).ready(function () {
    jQuery('body').delegate('.newcustomimage', 'change', function () {
        if (jQuery(this).val()) {
            jQuery(this).parent().parent().append('<div id="add_image_2508269_success" class="success-message validation-advice"> Image Uploded.</div>');
   }
});

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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pra*_* MS 9

为此,请按照以下说明

在你的HTML中添加这个

<input type="file" id="add_image_{{rand}}" data-rand={{rand}} class="newcustomimage" name="new_image" onchange="readURL(this);" value=""  />

<img id="previewImg" src="#" style="display: none;height: 200px; width: 200px;" >
Run Code Online (Sandbox Code Playgroud)

相同的java脚本将是.

function readURL(input) {

    if (input.files && input.files[0]) { 

        var reader = new FileReader(); 
        reader.onload = function (e) {
            jQuery('#previewImg').attr('src', e.target.result);
            jQuery('#previewImg').show();
        }
        reader.readAsDataURL(input.files[0]);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将适用于您的情况请尝试.