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
: 18513 At:- 6/1/2017 11:48:32 AM
C# Image upload ASP.NET







4 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.

UPDATE: To Upload files, in C# MVC you can consider well-explained articles also

1. (File Uploading using jQuery Ajax in MVC (Single or multiple file upload)https://qawithexperts.com/article/asp.net/file-uploading-using-jquery-ajax-in-mvc-single-or-multiple-f/98  

2. (Uploading files in MVC (Single/Multiple)https://qawithexperts.com/article/asp.net/uploading-files-in-aspnet-mvc-c-single-multiple-files/67  

3. (File uploading using DropZone.JS in MVC) https://qawithexperts.com/article/asp.net/file-uploading-using-dropzone-js-html5-in-mvc/81

Hope this will helps, thanks

1
At:- 6/3/2017 6:59:57 AM Updated at:- 2/16/2018 5:13:07 PM
works as I needed, upvoted your answer 0
By : jaiprakash - at :- 6/4/2017 11:25:12 AM


profileImage Answered by:- neena

For uploading file in asp.net mvc take a look at this well explained article

https://qawithexperts.com/article/asp.net/uploading-files-in-aspnet-mvc-c-single-multiple-files/67

 

1
At:- 10/27/2017 3:21:51 PM


profileImage Answered by:- user_2107228942

Hi 

Q. How we use tempdata in controller to controller in asp.net mvc.

0
At:- 11/7/2017 6:03:55 AM
I have asked a new question on your request, this thread is for "how to Upload image in MVC C#" related queries/solution 0
By : vikas_jk - at :- 11/7/2017 10:11:11 AM
here is the URL of your above Tempdata related question https://qawithexperts.com/questions/155/how-we-use-tempdata-in-controller-from-another-controller-in 1
By : vikas_jk - at :- 11/7/2017 10:21:08 AM


profileImage Answered by:- user_2119680103

hi when i upload image this is my problem"No files selected." can you help me plz?

0
At:- 12/22/2017 6:24:38 AM
are you using my above code, then Request.Files must have got your images, please check in form if you are using enctype = "multipart/form-data" with FormMethod.Post, please comment back and let me know if you still find issue, or please add a new question by linking this question and your current HTML form and C# code 0
By : vikas_jk - at :- 12/23/2017 5:58:36 PM






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