Loading ...

Upload File in ASP.net MVC

Who is online?  0 guests and 0 members
home  »  articles  »  Upload File in ASP.net MVC

Upload File in ASP.net MVC

(2589)
0
/5
Avg: 0/5: (0 votes)
Published: 7/14/2009 by  Anil Potter

you can upload file in MVC just create a sample MVC application and on the HomeController.cs file put the code in the CS file

public ActionResult UPLOAD (HttpPostedFileBase file)
        {
            if (file != null)
            {
                Random rand = new Random(); // generates the random number of the file
                int fName = rand.Next();
                var fileName = Path.Combine(Request.MapPath("~/App_Data"), fName.ToString()+ Path.GetExtension(file.FileName));
                file.SaveAs(fileName);
                return RedirectToAction("Index");// redirect to the index page
            }
            else
            {
                return View();
            }
        }

Right click on the UPLOAD and add a view UPLOAD and you can see the view in the ~/Home/UPLOAD.aspx

In the Upload page add the code

<form action="/Home/UPLOAD" method="post" enctype="multipart/form-data">
    <label>Filename: <input type="file" name="file" /></label>
    <input type="submit" value="Uplaod File" />
</form>

and run the code and you can see the uploaded file in the App_data folder. You can change the path as you like.

 

 

Comments (no comments yet)

Confirm

Product Spotlight

ASP.NET Hosting Spotlight

Most Recent Articles