我认为我的问题很简单,但我正在努力解决它。 当我上传图像文件时,它工作正常,但数据库上的路径是物理路径,如 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);
}
创建视图
<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>
DETAILS VIEW
<dt>
@Html.DisplayNameFor(model => model.File)
</dt>
<dd>
@Html.Image(@Model.File, "image")
</dd>
答案 0 :(得分: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;
答案 1 :(得分:0)
如何将虚拟路径分配给变量?
var fileName = Path.GetFileName(file.FileName);
var destination = $"~/Content/uploads/{fileName}";
var physicalPath = Server.MapPath(destination);
file.SaveAs(physicalPath);
然后只存储 目的地 变量的内容
答案 2 :(得分:0)
var phisicalPath = Path.Combine(("~/Content/uploads/"), fileName);
或
string filePath = @"~/Content/uploads/"
var phisicalPath = Path.Combine(filePath, fileName);