繁体   English   中英

图像控件asp.net中没有显示图像

[英]Image is not showing in image control asp.net

这是UI中的图像控件:

  <asp:Image ID="Image1" ImageUrl='<%# Bind("strCLogo") %>' runat="server" width="200" Height="200"/>

这里是C#代码,我从数据库(customerstbl)抓取图像的链接,但无法将其与图像控件绑定,我可以看到源中的图像链接,但它没有显示:

 protected void Page_Load(object sender, EventArgs e)
    {
      int nCID = Convert.ToInt32(  Session["nCID"].ToString());

      DataClasses1DataContext _dc = new DataClasses1DataContext();
      CustomersTbl _customer = new CustomersTbl();
      _customer = _dc.CustomersTbls.Where(a => a.nCID == nCID).FirstOrDefault();
     Image1.ImageUrl = _customer.strCLogo.ToString();

    }

这是我如何在数据库中保存图像的链接,似乎我在数据库中保存图像链接时有一个问题(它保存整个路径而不是本地目录路径和图像名称)

string s = Server.MapPath("~/Imageslogo/") + Path.GetFileName(LogoUpload.PostedFile.FileName);
            LogoUpload.SaveAs(s);

F:\\projects\\accounting\\Accounting2014\\Accounting2014\\Imageslogo\\10000120324‌​0.jpeg不是Image.ImageUrl属性的正确值,正确的值是相对路径,如~/Imageslogo/10000120324‌​0.jpeg

您需要保存数据库的相对路径,使用下面的代码获取相对路径

string imageLocation = string.Format("~/Imageslogo/{0}", Path.GetFileName(LogoUpload.PostedFile.FileName));

并将imageLocation保存到CustomersTbl表的strCLogo列。

将映像路径保存为相对路径,全局配置根路径

您将图像的路径存储为绝对路径。 这有几个原因很糟糕,主要原因是:

  • 如果将应用程序部署到具有不同文件结构的其他服务器,会发生什么? 你的绝对路径是错的
  • 如果您决定移动所有图像(但保留图像文件夹的结构)会发生什么? 再次,你的绝对路径将是错误的。

我建议您将相对图像路径存储在数据库中。 在这种情况下/Imageslogo/100001203240.jpeg 然后将图像路径(相对路径之前的部分)存储在Web.config文件中。 例如在appSettings

<appSettings>
    <add key="myApp.Imageroot" value="F:\projects\accounting\Accounting2014\Accounting2014" />
</appSettings>

您可以使用以下代码获取此appSetting值:

string myRoot = System.Configuration.ConfigurationManager.AppSettings.Get("myApp.Imageroot");

通过完整路径的这两部分,您可以:

  • 使用HTML输出中的相对路径,它可以在您的Web服务器上正常工作
  • 通过将appSettings中的根与数据库中的相对路径相结合来构造完整路径。 你可能会使用这个,你需要以编程方式操作图像或以其他方式访问实际文件,而不是仅仅将路径传递给客户端浏览器。
  • 通过更改appSetting轻松更改根目录

注意

ImageUrl ,如果你在后面的代码中设置ImageUrl属性,那么.aspxImageUrl属性就变得毫无意义。 所以删除它:

<asp:Image ID="Image1" runat="server" width="200" Height="200"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM