最近在網站首頁上想將Banner壁紙給做到後台上傳隨時更改的效果。遇到問題便是:將上傳的圖片路徑動態添加到首頁css代碼中,結果嘗試了網上提供的思路,更改相對路徑,換為url中“../../Content/”以及“./Content/”之類的,但實際操作並沒能實現新上傳的圖片路徑加載到css代碼中。首頁部分css代碼貼出:
1 /*--banner--*/
2 .banner {
3 background:url(../images/banner-1.jpg) no-repeat 0px 0px;
4 background-size: cover;
5 -webkit-background-size: cover;
6 -o-background-size: cover;
7 -ms-background-size: cover;
8 -moz-background-size: cover;
9 min-height: 600px;
10 }
首頁部分html貼出:
1 <div class="banner"> 2 <div class="container"> 3 <h2>Humanity ,Love ,Devotion</h2> 4 <h2></h2> 5 <p></p> 6 <a href="#service">快速獲取我們提供的服務</a> 7 </div> 8 </div>
之前思路是,將上傳的圖片路徑獲取後,保存在mysql數據庫中,然後寫一個分頁,在分頁裡將路徑讀出來,這時候將css裡background:url(../images/banner-1.jpg) no-repeat 0px 0px;換成了一個字段賦值;
關於實現字段賦值實現是這樣的:
1 @using TheOne.Models
2 @using TheOne.MySqlAccess
3 @{
4 SystemServiceAccess ssAccess = new SystemServiceAccess();
5 String BannerPicUrl = ssAccess.GetBannerPic();
6 }
BannerPicUrl被加在 background:url(../@BannerPicUrl) no-repeat 0px 0px;
折騰許久的相對路徑,沒能達到效果,於是我想出另一種實現思路,能不能將css保留原樣,而只要將css引入的圖片在文件系統裡進行更換、重命名。慶幸的是,asp.net 擁有強大的文件操作功能!於是我開始重新開始寫實現功能代碼。
這是核心功能,裡面有幾點需要說明:
1 [HttpPost]
2 public ActionResult AddBannerPic(HttpPostedFileBase file)
3 {
4 //上傳文章封面圖片
5 try
6 {
7 if (file != null && file.ContentLength > 0)
8 {
9 //文件路徑後要加後綴.jpg
10 string DeletePath =System.IO.Path.Combine(Server.MapPath( "~/Content/FrontEnd/images"),"Banner-1.jpg");
11 try
12 {
13 System.IO.File.Delete(DeletePath);//刪除指定文件目錄下的圖片
14 }
15 catch (Exception f)
16 {
17
18 throw f;
19 }
20
21 //重命名上傳的圖片名稱
22 string NewBannerPicName = "Banner-1.jpg";//指定新文件名
23 string Path = System.IO.Path.Combine(Server.MapPath("~/Content/FrontEnd/images"), NewBannerPicName);//更新前端Content文件夾下的目錄Banner-1圖片
24 file.SaveAs(Path);//存入新路徑
25 }
26 }
27 catch (Exception e)
28 {
29 throw e;
30 }
31
32 return View("Index");
33 }
這樣我刷新首頁時,就能看到我剛上傳的圖片,這樣的實現,沒有使用數據庫存儲,也沒有更改css相對路徑,只需要使用到文件操作(System.IO)。
項目演示地址:http://www.libertas.ren/