I am trying to upload images in MVC 5 but image not post to server side and
HTML Code is
below code is under form tag
<form action="~/Uerprofile/UploadPhotos" method="post" >
<div class="col-md-12 col-sm-12 form-grou">
<div class="col-md-5 col-sm-5 form-group">
<label class="label lbldesign">Upload Your Photos</label>
<input type="file" class="form-control" id="pphoto" name="pphoto" autofocus accept=".png,.jpeg,.jpg" />
<br />
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</div>
public ActionResult Uploadphotos(HttpPostedFileBase pphoto)
{
pphoto = Request.Files["pphoto"];
if (pphoto != null)
{
try
{
DataModel dm = new DataModel();
dm.Photo = converttobyte(pphoto);
TempData["error"] = "Photo Upload Successfully";
}
catch (Exception ex)
{
TempData["error"] = ex.Message;
RedirectToAction("EditProfile", "UserProfile");
}
return RedirectToAction("EditProfile", "UserProfile");
}
}
You need to make sure your <form>
as the attribute enctype="multipart/form-data" if you want to populate Request.Files
Using HTML helper:
@using (Html.BeginForm("ActionName",
"ControllerName",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
If you are not using HTML Helper then add the attribute to your form tag.
<form method="POST" enctype="multipart/form-data" action="/SomeUrl">
Try this it will be helpful
My View Code
@using (Html.BeginForm("Index", "ImportData", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="row">
<div id="radio" class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="input-group col-lg-4 col-md-4 col-sm-12 col-xs-12">
<input type="file" id="dataFile" name="upload" class="btn btn-info" />
</div>
</div>
</div>
<br />
<div class="row">
<div id="radio" class="col-lg-12 col-md-12 col-sm-12 col-xs-12" align="center">
<div class="input-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
<input type="submit" value="Upload" class="btn btn-primary" />
</div>
</div>
</div>
}
My Controller code
[HttpPost]
public ActionResult Index(HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
}
else
{
ModelState.AddModelError("File", "Please Upload Your file");
}
}
return View();
}
您的HTML没有<form>
标记,它告诉浏览器如何处理提交按钮的单击。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.