好吧所以我一直在尋找所有來到這個小小的代碼,並得到幾乎所有的工作。我可以上傳圖像並將其保存到創建的文件夾中。我可以保存其他值傳遞給數據庫。我現在的問題是,我想保存到數據庫的文件路徑,所以我可以調用它來在另一個頁面上顯示圖像。出於某種原因,它只會保存正在上傳的圖像名稱,而不是路徑。保存到數據庫的文件路徑,只保存文件名
當我調試一下,看看所有的獲得通過,當我的手錶添加到 file.SaveAs(pathLoc);
表達進行了評估,並沒有值無效
這裏是我的代碼「VE使用齋
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ImageInfo info, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
var pic = Path.GetFileName(file.FileName);
var pathLoc = Path.Combine(Server.MapPath("~/Uploads/") + pic);
file.SaveAs(pathLoc);
info.ImagePath = file.FileName;
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(info);
}
查看
<h2>Create</h2>
@using (Html.BeginForm("Create", "ImageInfoes", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="form-horizontal">
<h4>ImageInfo</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ImageName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ImageName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ImageName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ImageSize, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ImageSize, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ImageSize, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ImagePath, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input id="ImagePath" title="Upload a product image" type="file" name="file" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
型號
public partial class ImageInfo
{
public byte id { get; set; }
public string ImageName { get; set; }
public Nullable<long> ImageSize { get; set; }
public string ImagePath { get; set; }
}
任何將有助於充分。
info.ImagePath = file.FileName; => FileName將只會給你文件...名稱。 –
設置'pathLoc'而不是'file.Filename'? – Berkay
當我從file.FileName更改爲pathLoc db.SaveChanges();拋出和錯誤。 – whisk