Monday, May 14, 2012

File Upload Asp.net Mvc3.0


You need to add file html element and set the form type to multipart to upload files. For example, we are sending one file to UserFileController class and upload method with Post method. When user submits ok, it will upload file directly.


@using (Html.BeginForm("Upload", "UserFile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}

You can check request files to see their content.

public class UserFileController : Controller
{
    // Index of files
    public ActionResult Index()
    {
        return View();
    }
    
   // render the page
 public ActionResult Upload()
    {
     return View();
    }
    // Upload
    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        // You can verify that the user selected a file
        if (file != null && file.ContentLength > 0) 
        {
            // Filename is provided to you
            var fileName = Path.GetFileName(file.FileName);
            // you can simply save file to some folder with updated name
            fileName += Guid.NewGuid().ToString();
            //you can record some information if you want...
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); file.SaveAs(path); } // redirect back to the index action to show the form once again return RedirectToAction("Index"); } }

If you have multiple files, you can go through collection of files in the request stream to save them.


// Upload
    [HttpPost]
    public ActionResult Upload(int nothingreallyhereNeeded)
    {


try
                {
                    HttpFileCollectionBase hfc = Request.Files;
                    

                    if (hfc.Count > 0)
                    {
                        String h  = hfc.AllKeys.FirstOrDefault();
                        //multiple files
                        if (hfc[h].ContentLength > 0)
                        {
                             //we are recording info about file
                            CustomerFileRecord fileRecord = new CustomerFileRecord();
                            fileRecord.ReadStart = DateTime.UtcNow;
                   
                            Stream str = hfc[h].InputStream;
                            int fsize = 0;
                            if (str.Length > 0)
                            {
                                //just checking stream length
                                fileRecord.FileSize = (int)str.Length / 1000;
                            }
                            fileRecord.CreatedOn = DateTime.UtcNow;
                            fileRecord.Name = hfc[h].FileName;
                            fileRecord.FullName = DataFolder + fileRecord.Name;
                            hfc[h].SaveAs(DataFolder  + fileRecord.Name);
                             
                            db.CustomerFileRecords.AddObject(fileRecord);
                            db.SaveChanges();

                             
                        //do some file processing if you want.. or put into queue to process later.
                        

                            
                          return RedirectToAction("Index");  
} else { msg = "Empty file"; } } else { msg = "File is not attached"; } } catch (Exception ex) { logger.ErrorException("Upload data file"+ex.Message,ex); msg += "Error in processing data file: "+ex.Message; }
ViewBag.Message = msg;
return View();
}

4 comments:

  1. This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.

    http://www.mindstick.com/Articles/1d931eb6-5fa8-4509-a8f8-ce76c23f814f/?HTTP%20File%20Upload%20with%20ASP%20NET%20MVC%203

    http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=44

    ReplyDelete
  2. wow this saintly however ,I love your enter plus nice pics might be part personss negative love being defrent mind total poeple , check this out

    ReplyDelete
  3. The best article I came across a number of years, write something about it on this page. more info

    ReplyDelete
  4. This is very appealing, however , it is very important that will mouse click on the connection: check this out

    ReplyDelete

Hey!
Let me know what you think?