2015-04-05 72 views
2

我想通过JavaScript在文件输入中显示选定的图像。下面是我使用的代码如下所示:选择文件后显示图像

<label id="lblFileUploadProfile"> 
<asp:FileUpload runat="server" ID="ImageProfileUpload" /> 
<asp:Image runat="server" ID="ImgProfilePic" ImageUrl="img/user-5.png" /> 

我使用这个文件输入到上传图片,但不知道如何选择图像时显示选定的图像? 如何在使用JS完成上传时显示它?

+1

通过使用AJAX ..你有没有尝试什么吗? – walther 2015-04-05 13:52:09

+0

不,我没有! 如何? – 2015-04-05 13:54:30

+0

从学习如何使用谷歌开始,已经有很多例子了。基本原理如下所示 - 使用ajax启动上传,返回值为两个(或更多) - 如果上传成功并且上传图像的路径。然后只是更新图像的src ... – walther 2015-04-05 14:05:58

回答

2

试试这个办法:

<img id="blah" class="photo" ImageUrl="img/user-5.png" /> 
<label for="imgInp" class="custom-file-upload"> 
    <i class="fa fa-cloud-upload"></i>Add Image 
</label> 
<input type='file' id="imgInp" name="image" /> 


<script> 
//Preview & Update an image before it is uploaded 
    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); 
    }); 
</script> 


<style type="text/css"> 
input[type="file"] { 
    display: none; 
} 

.custom-file-upload { 
    border: 1px solid rgb(197, 197, 197); 
    border-radius: 4px 4px 4px 4px; 

    display: inline-block; 
    padding: 6px 12px; 
    cursor: pointer; 
    float: right; 
    width: 5.25em; 
    margin-left:200px; 
} 

.photo{ 
    width: 7em; 
    height: 9em; 
    border: 1px solid rgb(197, 197, 197); 
    border-radius: 4px 4px 4px 4px; 
    float:right; 
} 
</style> 

希望这有助于...

+0

你确定这与你一起工作? – 2015-04-05 14:02:21

+0

我在我的MVC项目中使用它,并且完美地工作。请试试这个,让我知道它是否有效。 – 2015-04-05 14:03:17

+0

我没有使用MVC,我使用的是空白网站,并没有与我一起工作 它打开选择对话框,但它没有做任何事情,当我选择一个图像 – 2015-04-05 14:09:25

相关问题