Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a MultipartForms in Which I Could upload an Image and other form values.While, the form values are rightfully received through the FormCollection Property whereas the Upload file always shows the null value in HttpPostedFileBase Property.I go through forums but I couldn't get Where went Wrong. Here, Is What I done Please go through it and Said what Went Wrong.Thanks friend.

What I have tried:

cshtml:



@using (Html.BeginForm("Create", "StaffRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="StaffImage" id="StaffImage" />
}



Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection,HttpPostedFileBase File)
{
try
{
// TODO: Add insert logic here


StaffRegistration StaffReg = new StaffRegistration();

StaffReg.FirstName = collection["FirstName"].ToString();
StaffReg.LastName = collection["LastName"].ToString();
StaffReg.DateOfBirth = DateTime.Parse(collection["DateofBirth"]);
StaffReg.Nationality = collection["Nationality"].ToString();
StaffReg.Gender = collection["Gender"].ToString();
StaffReg.MaritalStatus = collection["MaritalStatus"].ToString();
StaffReg.BloodGroup = collection["BloodGroup"].ToString();
StaffReg.StaffName = collection["StaffName"].ToString();
StaffReg.MiddleName = collection["MiddleName"].ToString();
HttpPostedFileBase file = Request.Files["StaffImage"];

StaffRegistrationBusSer StaffRegBusSer = new StaffRegistrationBusSer();
StaffRegBusSer.AddStaffReg(StaffReg,file);

return RedirectToAction("Index");
}

DataLayer:

public bool AddStaffRegistraiton(StaffRegistration staffRegistration,HttpPostedFileBase File)
{
staffRegistration.StaffImage = ConvertToByte(File);

using(SqlConnection Con = new SqlConnection(ConnectionString))
{
SqlParameter paramImage = new SqlParameter();
paramImage.ParameterName = "@StaffImage";
paramImage.Value = staffRegistration.StaffImage;
Cmd.Parameters.Add(paramImage);
Con.Open();
Cmd.ExecuteNonQuery();

}
return true;
}

ConvertToByte function:

public byte[] ConvertToByte(HttpPostedFileBase Image)
{
byte[] imagebyte = null;
BinaryReader Reader = new BinaryReader(Image.InputStream);
imagebyte = Reader.ReadBytes((int)Image.ContentLength);
return imagebyte;
}
Posted
Updated 6-Aug-16 23:58pm
v4

Greetings Mohammed Asarudeen R

Please find the solution to your issue, with some suggestions.

My example uses a helper method with the following code:
C#
public bool ValidateFile(HttpPostedFileBase file)
        {
            switch(file.ContentType)
            {
                // Example: return valid = true for following file types:
                case ("image.gif"):
                case ("image/jpg"):
                case ("image/png"):
                    return true;

                // Otherwise if anything else, return false
                default: return false;
            }
        }


Solution 1 - using html form elements:
This solution is similar to your example code with no view model, but see option 2 for a view model approach.
1. cshtml
HTML
@using (Html.BeginForm("FileUploadNoModel", "Home", FormMethod.Post, new { encType = "multipart/form-data" }))
{
    <span>Choose a file: </span>
    <input type="file" id="fileUpload" name="fileUpload" />
    <input type="submit" value="Upload"/>
}

2. Controller
C#
[HttpPost]
        // Note here that I have used only FormCollection parameter
        public ActionResult FileUploadNoModel(FormCollection collection)
        {
            if(ModelState.IsValid)
            {
                // Note here: the file is actually transported in the Request object,
                // not the FormCollection object, or as in your example;
                // "HttpPostFileBase" parameter.
                var postedFile = Request.Files["fileUpload"];
                var fileIsValid = ValidateFile(postedFile);
            }
            return View("Index");
        }


Solution 2 - With a View model class
1. cshtml
HTML
@model MVCFileupload.Models.FileUploadModel
@using (Html.BeginForm("FileUploadWithModel", "Home", FormMethod.Post, new { encType = "multipart/form-data" }))
{
    <!-- Note here I have used TextBoxFor the model property -->
    @Html.TextBoxFor(m => m.File, new { type = "file" <!-- this attribute is important --> })
    <input type="submit" value="upload" />
}

2. View Model class
C#
namespace MVCFileupload.Models
{
    public class FileUploadModel
    {
        public HttpPostedFileBase File { get; set; }
    }
}

3. Controller
C#
[HttpPost]
        public ActionResult FileUploadWithModel(FileUploadModel model)
        {
            if(ModelState.IsValid)
            {
                var postedFile = model.File;
                var fileIsValid = ValidateFile(postedFile);
            }
            return View("Index");
        }


I trust these solutions will assist in your task.

All the best.
 
Share this answer
 
v2
@using (Html.BeginForm("Create", "StaffRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
HTML
<div class="form-group">
               <div class="col-md-offset-2 col-md-10">
                   <input type="file" name="StaffImage" id="StaffImage" />
               </div>
           </div>

}
Before I just using the beginform which is nested inside the view beginform function later I Modified the beginform function of the view. and delete the nested beginform function.Actually, What happened is I jus using multipart/formdata for only fileupload control.Later, I realized that Which could be included at View Level.Thanks friends for Your Suggestion..


This is Modified one

HTML
@using (Html.BeginForm("Create", "StaffRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>StaffRegistration</h4>
            <hr />
            @Html.ValidationSummary(true)

            <div class="form-group">
                @Html.LabelFor(model => model.StaffId, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.StaffId)
                    @Html.ValidationMessageFor(model => model.StaffId)
                </div>
            </div>

HTML
<div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="file" name="StaffImage" id="StaffImage" />
                </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>
}
 
Share this answer
 
Comments
njammy 8-Aug-16 5:25am    
While I am happy to see you have solved it, it's not cool to accept an answer, then undo the accept, only to add your own answer. If my answer helped then please mark as accepted for other developers facing this issue in the future, for their benefit.
Mohammed Asarudeen R 8-Aug-16 6:09am    
oh!I'm Sorry Dude! Yes your perception is very right. I acknowledge your answer which will help many right! Thank you for your Suggestion friend.Have a Great Day
njammy 8-Aug-16 7:08am    
Thank you all the best

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900