2016-04-25 55 views
0

我的問題我相信很簡單,但我很努力。 當我上傳圖像文件時,它工作正常,但數據庫上的路徑是物理的,如C:// user/pictures/blabla ....。 我想將其更改爲虛擬路徑(〜/ ...)。 當我手動將數據庫路徑更改爲虛擬路徑時,映像顯​​示爲空。 在此先感謝您的幫助。 這裏是我的代碼:在數據庫中存儲物理路徑而不是虛擬的

控制器

public ActionResult Create(DriverReg model, HttpPostedFileBase file) 
     { 
      if (ModelState.IsValid) 
      { 
       if (file != null && file.ContentLength > 0) 
       { 
        var fileName = Path.GetFileName(file.FileName); 
        var phisicalPath = Path.Combine(Server.MapPath("~/Content/uploads/"), fileName); 
        file.SaveAs(phisicalPath); 
        DriverReg newRecord = new DriverReg(); 
        newRecord.FullName = model.FullName; 
        newRecord.Address = model.Address; 
        newRecord.Postcode = model.Postcode; 
        newRecord.Contact = model.Contact; 
        newRecord.Email = model.Email; 
        newRecord.County = model.County; 
        newRecord.File = phisicalPath; 
        newRecord.Date = DateTime.Now; 

        db.DriverRegs.Add(newRecord); 
        db.SaveChanges(); 
        return RedirectToAction("Index"); 
       } 
      } 

      return View(model); 
     } 

CREATE VIEW

<div class="form-group"> 
       @Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" }) 
       <div class="col-md-10"> 
        <input type="file" class="file-input" name="file" /> 
        @Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" }) 
       </div> 
      </div> 

詳情查看

<dt> 
       @Html.DisplayNameFor(model => model.File) 
      </dt> 

      <dd> 
       @Html.Image(@Model.File, "image") 
      </dd> 

回答

2

在調用Server.MapPath之前存儲虛擬路徑,然後在數據庫記錄中使用該路徑。

var fileName = Path.GetFileName(file.FileName); 
var combinedVirtualPath = Path.Combine("~/Content/uploads", fileName); 
var phisicalPath = Server.MapPath(combinedVirtualPath); 
file.SaveAs(phisicalPath); 
DriverReg newRecord = new DriverReg(); 
newRecord.FullName = model.FullName; 
newRecord.Address = model.Address; 
newRecord.Postcode = model.Postcode; 
newRecord.Contact = model.Contact; 
newRecord.Email = model.Email; 
newRecord.County = model.County; 
newRecord.File = combinedVirtualPath; 
newRecord.Date = DateTime.Now; 
+0

感謝斯蒂芬,我已經試過你的代碼,並沒有工作,它導致一個錯誤**文件是一個物理路徑,但預計虛擬路徑** – prezequias

+0

謝謝你們,從阿什利的更新是完美的。你保存了我的日子 – prezequias

0

如何將虛擬路徑分配給變量?

var fileName = Path.GetFileName(file.FileName); 
var destination = $"~/Content/uploads/{fileName}"; 
var physicalPath = Server.MapPath(destination); 
file.SaveAs(physicalPath); 

然後只存儲目的地的內容變量

+0

謝謝DVK,我已經試過了你的答案,但是仍然是db上的物理路徑,任何其他的消聲? – prezequias

0
var phisicalPath = Path.Combine(("~/Content/uploads/"), fileName); 

string filePath = @"~/Content/uploads/" 
var phisicalPath = Path.Combine(filePath, fileName);