2015-04-05 76 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

相關問題