Reputation: 193
I'm trying to upload images into my App_Data folder.I've used HttpPostedFileBase, but it always returned null for some reason. Here is my Create method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult mkCreate(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
}
return View();
}
Here is my view (Create.cshtml):
@using (Html.BeginForm("mkCreate", "Resim", FormMethod.Post, new { enctype= "multipart/form-data" }))
{
<table>
<tr>
<td>Image:</td>
<td><input type="file" name="Images" id="Images" multiple /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Upload" /></td>
</tr>
</table>
}
Could you please help me upload images into my App_Data folder? Thanks in advance.
Upvotes: 0
Views: 934
Reputation: 6398
TRY WITH THIS add enctype
public ActionResult Create(HttpPostedFileBase file)
{
//Rest of the code
}
View
@using (Html.BeginForm("YourMethod", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="Images" multiple />
}
Upvotes: 0
Reputation: 440
Your Image model could be something like this:
public class Image
{
public IEnumerable<HttpPostedFileBase> Images { get; set; }
}
Your controller should have an action like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Image image)
{
foreach (var file in image.Images)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
}
}
ViewBag.Message = "Image(s) uploaded successfully";
return View();
}
And finally your view could be something like this:
@model AppName.Models.Image
@{
ViewBag.Title = "Index";
}
<h2>Image Upload Test</h2>
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype "multipart/form-data" }))
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
{
<table>
<tr>
<td>Image:</td>
<td><input type="file" name="Images" id="Images" multiple /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Upload" /></td>
</tr>
</table>
}
Upvotes: 1