Rajmohan
Rajmohan

Reputation: 11

how to Get ImageUrl of a asp image control whose image is set by jquery in the client side?

i have an image and button server controls in the aspx page.

<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />  
<asp:Image ID="impPrev" runat="server" Height="200px" /> 
<input type="file" name="ImageUpload" id="ImageUpload" onchange="ShowPreview(this)" />

i also have a html file type input control using which i am able to change the imageUrl of the asp image control from client side using jquery like

function ShowPreview(FileUpload1) {
   if (FileUpload1.files && FileUpload1.files[0]) {
      var file = FileUpload1.files[0];
      var ImageDir = new FileReader();
      if (file) {
         ImageDir.readAsDataURL(file);
      }  
      ImageDir.addEventListener('load', function () {
         $('#impPrev').attr('src', ImageDir.result);
      });
   }
}

if i am trying to get url of newly set image from code-behind like

protected void btnUpload_Click(object sender, EventArgs e) {
   var path = impPrev.ImageUrl;
}

empty string is being returned to "path". how can i get the actual path of the image set by jquery??

Upvotes: 1

Views: 885

Answers (1)

Aundy
Aundy

Reputation: 66

I believe you cannot get the value to server side because the form is not post back for the information to reach server. Moreover the image is not stored any where in the server to get the URL path from server side. But you can get the Image attributes such as Name, client path etc by using hidden field and setting the required value to that field.

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />  
        <asp:Image ID="impPrev" runat="server" Height="200px" /> 
        <input type="file" name="ImageUpload"   id="ImageUpload" onchange="ShowPreview(this)" />
       ** <input type="hidden" runat="server" id="myhid" />**
    </div>
    </form>
</body>
</html>

function ShowPreview(FileUpload1) {
    if (FileUpload1.files && FileUpload1.files[0]) {
        var file = FileUpload1.files[0];
        var ImageDir = new FileReader();
        if (file) {
            ImageDir.readAsDataURL(file);
        }
        ImageDir.addEventListener('load', function () {
        $('#impPrev').attr('src', ImageDir.result);
        $('#myhid').val(file.name);
        }); 
    }
}

 protected void btnUpload_Click(object sender, EventArgs e)
        {
            //var path = impPrev.ImageUrl;
            var test = myhid.Value;
        }

Upvotes: 1

Related Questions