Reputation: 397
I am beginner in asp.net and trying to upload the image in my project Images folder but it is not uploading it in desired folder. Anybody please give me suggestion.
Create.cshtml
@using (Html.BeginForm("Create", "Lenses", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>lens</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.lens_img, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="file" id="file" style="width: 100%;" />
</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>
}
Controller.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "lens_img")] lens lens, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Content/Images/")
+ file.FileName);
lens.lens_img = file.FileName;
}
db.lenses.Add(lens);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(lens);
}
Upvotes: 0
Views: 4465
Reputation: 62488
If file is reaching the controller action and file
parameter is not null, then you should be using Path.Combine
method to generate the correct path, do not use string concatenation for this, you should try it in following way:
file.SaveAs(Path.Combine(HttpContext.Server.MapPath("~/Content/Images/"), file.FileName);
For more clarity, let's break in to two steps:
var mappedPath = HttpContext.Server.MapPath("~/Content/Images/");
file.SaveAs(Path.Combine(mappedPath, file.FileName);
Also have a look at this answer as well which is related.
Hope it helps!
Upvotes: 1