【问题标题】:Change Image Url at button click单击按钮更改图像 URL
【发布时间】:2015-05-09 00:29:32
【问题描述】:

在我的 asp.net 页面中,我有 Image control ,其中 myimage.png 将在页面加载时显示。要求如下, 使用文件上传控件浏览图像并单击上传按钮,需要在图像控件中显示即时预览。浏览图片后点击上传按钮,会删除已有的“myimage.png”,新图片会保存到同名的服务器路径中,需要在图片控件中显示预览。

问题是保存图像后,图像控件没有立即显示新图像。 要查看图像页面需要重新加载。代码如下, 在aspx页面中,

<asp:Image ID="imgLogo"  style="margin-left: -299px;" ImageUrl="~/images/myimage.png" runat="server" />

代码如下,

protected void btnUpload_Click(object sender, EventArgs e)
{
    string filePath = FileUpload1.PostedFile.FileName;
    File.Delete(Server.MapPath(@"~\images\myimage.png"));
    FileUpload1.SaveAs(Server.MapPath(@"~\images\myimage.png"));
    imgLogo.ImageUrl = Server.MapPath(@"~\images\myimage.png");
 }

问候

【问题讨论】:

    标签: c# asp.net image file-upload


    【解决方案1】:

    您的页面必须重新加载的原因是因为 ASP.NET 代码是在服务器上执行的。因此,例如,每次您单击内部带有服务器端代码的按钮时,请求都会发送到服务器,服务器会执行您的代码并返回正确的响应。基本上:必须重新加载一些东西。不过,它不必是整个页面。您可以使用 Script ManagerUpdate Panel 等 AJAX 扩展程序强制浏览器仅重新加载特定页面。

    示例(aspx 页面):

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server" Text="Click the button."></asp:Label>
                    <br />
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Hello World" />     
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
        </form>
    </body>
    </html>
    

    OnClick 事件:

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "Hello world!";
    }
    

    此外,您可以使用 UpdatePanel 的 Update() 方法强制面板更新其内容。

    【讨论】:

      【解决方案2】:

      这看起来像是浏览器缓存问题。

      url和修改图片文件之前的完全一样,所以缓存会使用原来命名的文件(在它的缓存中)来显示。

      您可以通过向 url 添加一些额外的(但未使用的)内容来克服这个障碍:

      protected void btnUpload_Click(object sender, EventArgs e)
      {
          // Do your upload stuff here...
          imgLogo.ImageUrl = "~/images/myimage.png?" + DateTime.Now;
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-21
        • 2013-11-05
        • 1970-01-01
        • 1970-01-01
        • 2011-12-14
        • 2012-07-07
        • 2014-04-17
        相关资源
        最近更新 更多