【问题标题】:How to get relative path of image for src attribute如何获取 src 属性的图像的相对路径
【发布时间】:2013-08-19 17:22:10
【问题描述】:

我想在我的 asp.net 网页上显示图像列表。 图片位于文件夹中。 我的aspx代码是这样的

   <asp:ListView runat="server" ID="lvPicturePaths">
   <ItemTemplate>
     <img src="<%# Container.DataItem %>" />
   </ItemTemplate>
    </ListView>

在我后面的代码中:

  private void GetImagePaths()
   {
      List<string> pathForPictures=new List<string>();
    var path=Server.MapPath("~/images/");
  foreach(var PP in Directory.GetFiles(path))
    {
    pathForPictures.Add(PP);
    }
    lvPicturePaths.DataSource=pathForPictures;
    lvPicturePath.DataBind();
 }

问题是img标签的src属性需要相对路径,比如localhost/images... 现在我得到类似: C:\Inetpub\wwwroot\images\image1.jpg

【问题讨论】:

    标签: asp.net path


    【解决方案1】:

    你可以使用:

    pathForPictures.Add(
        Page.ResolveClientUrl(
            System.IO.Path.Combine(
                "~/images/",
                System.IO.Path.GetFileName(PP)
            )
        )
    );
    

    或者不是做一个循环:

    private void GetImagePaths()
    {
        const string path = "~/images/";
        var pictures =
            Directory.GetFiles(Server.MapPath(path))
                .Select(p => 
                    Page.ResolveClientUrl(Path.Combine(path, Path.GetFileName(p))));
        lvPicturePaths.DataSource = pictures;
        lvPicturePath.DataBind();
    }
    

    【讨论】:

    • 仅供参考 - GetImagePaths 实际上并不获取图像路径。也许您应该将其重命名为 BindPicturePaths 或让它返回 IEnumerable 并将其绑定到其他地方?
    【解决方案2】:

    尝试 Page.ResolveUrl 而不是 Server.MapPath

    【讨论】:

      【解决方案3】:

      使用ResolveUrl

      试试这个代码

      this.ResolveUrl("~/images/")
      

      而不是

      Server.MapPath("~/images/");
      

      或者干脆试试ResolveUrl("~/images/")

      更多细节,请参阅Path这个很好的解释

      【讨论】:

        猜你喜欢
        • 2014-02-15
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-14
        • 2011-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多