2014-05-01 126 views
1

我試圖上傳圖像到我的文件夾,並在視圖中顯示。 我的控制器:顯示上傳的圖像asp.net mvc

[HttpPost] 
    public ActionResult Upload(HttpPostedFileBase file) 
    { 
     if (file != null) 
       { 
        string pic = System.IO.Path.GetFileName(file.FileName); 
        string path = System.IO.Path.Combine(Server.MapPath("~/images"), pic); 
        file.SaveAs(path); 
        ViewBag.Path = path; 

       } 
      return View(); 
     } 

我的觀點:

@{ 
    ViewBag.Title = "Upload"; 
} 

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, 
          new { enctype = "multipart/form-data" })) 
{ 
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 

} 

<h2>Upload</h2> 

<img src="@ViewBag.path" alt="Image"/> 

通過這樣做,圖像是不是在我看來,只有替代文字。生成的HTML源代碼:

<img src="C:\Users\D Stag\Documents\Visual Studio 2012\Projects\Data\Web\images\1232743916lituviai23afp.jpg"/> 

圖像被正確保存,它存在於該文件夾中。

+0

不能使用物理文件路徑SRC或HREF ......你需要使用絕對或相對路徑。 – MikeSmithDev

回答

3

代替 -

ViewBag.Path =路徑;

嘗試這種方式 -

ViewBag.Path = String.Format("/images/{0}", pic); //output should be "~/images/image1.jpg" 

UPDATE:沒有必要爲 「〜」 的路徑。然後圖像顯示。

+0

沒有幫助。獲取soutce代碼: user3450929

+0

需要更改爲@ Url.content(@ Viewbag.path),它的工作原理,謝謝! – user3450929

+0

@ user3450929,實際上路徑中不需要「〜」。我的答案已更新,現在它應該可以正常工作。請嘗試。也不需要使用@ Url.Content(),路徑應該可以正常工作。 – ramiramilu

0

嘗試這樣的:

<img src="@string.Format("/Image/{0}",pictue._id.ToString())" alt="@pictue.FileName" /> 
+0

請您詳細解釋代碼,以便其他人更容易理解您的解決方案? – wmk