2016-04-25 15 views
0

私の問題私は単純だと信じていますが、私はそれに苦労しています。 イメージファイルをアップロードすると正常に動作しますが、データベースのパスはC:// user/pictures/blabla ....のように物理的なものになります。 仮想パス(〜/ ...)に変更したいと思います。 データベースパスを手動で仮想パスに変更すると、イメージが表示されます。 ご協力いただきありがとうございます。 は、ここに私のコードです:仮想パスの代わりに物理パスをデータベースに保存

CONTROLLER

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詳細ビュー

<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> 

VIEW

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

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

答えて

2

Server.MapPathを呼び出す前に仮想パスを格納し、その仮想パスをDBレコードで使用します。

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); 
関連する問題