how to upload image in C# MVC


I have a new question, I would like to save image in my .NET MVC application from razor view, but as i am new mvc C# developer i don't have much knowledge in it.
As i understand till now, i need to send form with method post and enctype ="multipart/form-data"

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" })
{

 <input type="file" name="ImageFile" id="ImageFile" />

<input type="submit" value="Submit" id="Submit" />
}

There are sevaral methods on many websites related to ajax, C# etc, but i want the simplest one , which is easier to understand, and can be implemented quickly.


Asked by:- jaiprakash
1
: 621 At:- 6/1/2017 11:48:32 AM
C# Image upload ASP.NET






1 Answers
profileImage Answered by:- vikas_jk

yes your form is correct, you can now write this code in your controller to get the image in the back end

 // This code can be used for multiple files upload also
       [HttpPost]
        public ActionResult ImageUpload()
        {
           
            if (Request.Files.Count > 0)
            {
                try
                {
                    //  Get all files from Request object  
                    HttpFileCollectionBase files = Request.Files;
                    var savedurl = "";
                    for (int i = 0; i < files.Count; i++)
                    {
                        //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";  
                        //string filename = Path.GetFileName(Request.Files[i].FileName);  

                        HttpPostedFileBase file = files[i];
                        string fname;

                        // Checking for Internet Explorer  
                        if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                        {
                            string[] testfiles = file.FileName.Split(new char[] { '\\' });
                            fname = testfiles[testfiles.Length - 1];
                        }
                        else
                        {
                            fname = file.FileName;
                        }
                        string subPath = "~/Images/Upload/"; 

                        bool exists = System.IO.Directory.Exists(Server.MapPath("~/Images/Upload/"));

// if Folder doesn't exists create it
                        if (!exists)
                        { 
System.IO.Directory.CreateDirectory(Server.MapPath("~/Images/Upload/")); 
}
                        // Get the complete folder path and store the file inside it.  
                        fname = Path.Combine(Server.MapPath("~/Images/Upload/"), fname);

                       //save file on server
                        file.SaveAs(fname);
//you can save it in database also if you need it, but it is not recommended solution
                    }
                    // Returns message that successfully uploaded  
                    return Json(new { MSG="File Uploaded Successfully!" , SAvedUrl= savedurl },JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    return Json("Error occurred. Error details: " + ex.Message);
                }
            }
            else
            {
                return Json("No files selected.");
            }
        }

Saving files on a server is better than saving it database, as it increases database calls.

hope this will help, thanks

1
At:- 6/3/2017 6:59:57 AM
works as I needed, upvoted your answer 0
By : jaiprakash - at :- 6/4/2017 11:25:12 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use
Amazon Deals

Jobs from Indeed