图像上传和显示没有页面刷新jquery mvc

时间:2018-04-07 17:49:00

标签: javascript jquery image-uploading

我尝试了一些解决方案,以避免图像上传(客户端)上的页面刷新并使用jquery显示,但它不起作用。这是我的图片上传和显示代码:

 $("input[type='image']").click(function() {
            $("input[id='my_file']").click();
        });
        function readURL(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    $('#imgUser').attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        $("#my_file").change(function() {
            readURL(this);
        });

这项工作退出了不错,但问题是,它在上传图片时会刷新表格,因此我的模型(其他输入字段)很清晰。是否可以使用我当前的代码限制图像上传和显示时的表单刷新?任何建议和帮助都是值得赞赏的。谢谢。

我在这里添加了我的Html(Cshtml)代码图片上传:

<input type="image" id="imgUser" class="profile-user-img img-responsive img-circle" src="~/CommonResources/images/no-Image.jpg" alt="User profile picture">
<input type="file" id="my_file" name="files" style="display: none;" />   

1 个答案:

答案 0 :(得分:0)

检查这是否是您想要的。

HTML:

   <form id="form1" runat="server">
        <input type="text" name="name" /><br/>
        <input type='file' id="imgInp" style="display:none" />
        <img id="blah" style="border-radius:50%" src="http://via.placeholder.com/100x100" alt="your image" height="100px" width="100px" />
    </form>

Javascript(Jquery):

//select file - image
$('#blah').click(function() {
  $('#imgInp').click();
})

//preview the image
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() {
  readURL(this);
});

这是一个jsfiddle:https://jsfiddle.net/xpvt214o/72211/

注意:我没有看到任何页面刷新。您的代码对我来说似乎很好