Reputation: 61
I'm trying to upload picture to a folder. I have already try all answers here. Here is my code:
Controller:
[HttpPost]
public ActionResult UploadImage(HttpPostedFile uploadFile)
{
if (uploadFile != null)
{
string ImageName = System.IO.Path.GetFileName(uploadFile.FileName);
string Path = Server.MapPath("~/Content/Images/" + ImageName);
// save image in folder
uploadFile.SaveAs(Path);
db.SaveChanges();
}
return View();
}
View:
@using (Html.BeginForm("UploadImage", "Quizs", FormMethod.Post, new { enctype = "multipart/form-data " }))
{
<div>
<input type="file" name="uploadFile" /> <br />
<input type="submit" value="Upload" />
</div>
}
When I submit that form i get NULL in Controller (uploadFile is null). Please help me and tell me what is wrong.
Thank you
Upvotes: 2
Views: 3220
Reputation: 674
I Suggest following Code:
My View Page:
Here,I'm using model property for Uploading Image Called "uploadFile"
.
@model Users
@using (Html.BeginForm("UploadImage", "Quizs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<input type="file" id="uploadFile" name="uploadFile">
@Html.ValidationMessageFor(m => m.uploadFile)
<button type="submit">Submit</button>
}
My Model Class:
This is my model class which has a property called "uploadFile"
as HttpPostedFileBase
DataType.
public partial class Users
{
public HttpPostedFileBase uploadFile { get; set; }
}
My Controller Page:
Here,I'm using Users model class as input param which has my property and using UploadUserAvatar()
method for Uploading a image in folder in particular path called "~/Content/Images"
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Registration(Users user)
{
if (ModelState.IsValid)
{
UploadUserAvatar(user.uploadFile);
return View();
}
}
protected void UploadUserAvatar(HttpPostedFileBase image)
{
HttpPostedFileBase file = image;
if (file != null)
{
if (!Directory.Exists(Server.MapPath("~/Content/Images")))
Directory.CreateDirectory(Server.MapPath("~/Content/Images"));
string _fileName = Path.GetExtension(file.FileName);
string _path = System.IO.Path.Combine(Server.MapPath("~/Content/Images/"), _fileName);
file.SaveAs(_path);
}
}
Upvotes: 0
Reputation: 61
Thanks all for answers! Problem was extra space in
new { enctype = "multipart/form-data " }
Upvotes: 4
Reputation: 149
It should be "HttpPostedFileBase" instead of "HttpPostedFile"..
Upvotes: 3
Reputation: 383
I think you have a problem with routing. you must create a model that has a property of type HttpPostedFileBase
(not HttpPostedFile
) and name of uploadFile, and set your action methods argument to that model, a model like this:
public class FileSaveModel
{
public HttpPostedFileBase uploadFile {get; set;}
}
and then change your actions argument to:
public ActionResult UploadImage(FileSaveModel model)
Upvotes: 0