Reputation: 267
My problem I believe is simple, but I am struggling with it. When I upload image files, it works fine, but the path on database is physical one, like C://user/pictures/blabla.... . I would like to change it to virtual path (~/...). The images are displyed when I change manually the database path to virtual one. Thanks in advance for any help. Here are my codes:
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 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>
DETAILS VIEW
<dt>
@Html.DisplayNameFor(model => model.File)
</dt>
<dd>
@Html.Image(@Model.File, "image")
</dd>
Upvotes: 0
Views: 179
Reputation: 967
var phisicalPath = Path.Combine(("~/Content/uploads/"), fileName);
or
string filePath = @"~/Content/uploads/"
var phisicalPath = Path.Combine(filePath, fileName);
Upvotes: 0
Reputation: 3540
Store the virtual path before you call Server.MapPath on it, then use that in your DB record.
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;
Upvotes: 2
Reputation: 2792
How about just assigning the virtual path to a variable?
var fileName = Path.GetFileName(file.FileName);
var destination = $"~/Content/uploads/{fileName}";
var physicalPath = Server.MapPath(destination);
file.SaveAs(physicalPath);
Then just store the contents of the destination variable
Upvotes: 0