C# 遍歷文件夾及子目錄下全部圖片.

要求:取指定目錄下面的全部圖片,以表格的型式展現並顯示該圖片的相對路徑。javascript

服務端代碼:前端

 public partial class ViewIcon : System.Web.UI.Page
    {
        JArray ja = new JArray(); //定義一個數組
        public string info = string.Empty; 
        protected void Page_Load(object sender, EventArgs e)
        {
            var path1 = System.AppDomain.CurrentDomain.BaseDirectory;//獲取程序集目錄
            string path = Path.Combine(path1, "Image", "menu");//Path.Combine 將3個字符串組合成路徑
            var images = Directory.GetFiles(path, ".", SearchOption.AllDirectories).Where(s => s.EndsWith(".png") || s.EndsWith(".jpg") || s.EndsWith(".gif"));
            //images = Directory.GetFiles(path, "*.png|*.jpg", SearchOption.AllDirectories);
            //Directory.GetFiles 返回指定目錄的文件路徑 SearchOption.AllDirectories 指定搜索當前目錄及子目錄
            
            //遍歷string 型 images數組
            foreach (var i in images){
                var str = i.Replace(path1, "");//獲取相對路徑
                var path2 = str.Replace("\\", "/");將字符「\\」轉換爲「/」
                ja.Add(path2);
            }

            info = Newtonsoft.Json.JsonConvert.SerializeObject(ja);//序列化爲String
        }
    }

前端代碼:java

<script type="text/javascript">
     $(function(){
         var images = <%=info%>;
        var list = [];
        list.push("<table>");
        list.push("<thead>");  
        list.push("<tr>");  
        list.push("<td>圖標</td>");  
        list.push("<td>路徑</td>");  
        list.push("<td>圖標</td>");  
        list.push("<td>路徑</td>");
        list.push("</tr>"); 
        list.push("</thead>");
        list.push("<tbody>");
        $.each(images, function (a,b) {
            if((a+1)%2==0){
                list.push("<td>"+"<img width='50' height='50' src = '../../" + b + "'></td>");
                list.push("<td>"+b+"</td>");
                list.push("</tr>");  
            }
            if((a+1)%2!=0){
                list.push("<tr>");  
                list.push("<td>"+"<img width='50' height='50' src = '../../" + b + "'></td>");
                list.push("<td>"+b+"</td>");
            } 
        })
        list.push("</tbody>");
        list.push("</table>");
        list.push("<br>");
        var images = list.join("");
        $("#imgs").append(images); 
    })

</script>

 

效果圖以下:
20170104.jpg數組

相關文章
相關標籤/搜索