Wednesday, January 29, 2014

how to upload and download file in MVC4?


 <input type="file" name="fup" id="fup"/>
Upload File:
----------------
Random rdm = new Random();
            HttpPostedFileBase fup = Request.Files["fup"];
            string uploadedFileName = string.Empty;
            string path = string.Empty;
            if (fup.ContentLength > 0)
            {
                string no = Convert.ToString(DateTime.Now.Millisecond * rdm.Next(10000));
                string extension = System.IO.Path.GetExtension(fup.FileName).ToString();
                string fname = System.IO.Path.GetFileNameWithoutExtension(fup.FileName)+"_"+no;
                uploadedFileName = fname.Replace(" ", "_") + extension;
                path = Path.Combine(Server.MapPath("~/Uploads/"), uploadedFileName);
                fup.SaveAs(path);
            }


Download File:
-------------------

            var contentDisposition = string.Format("attachment; filename={0}", file);
            HttpContext.Response.AddHeader("Content-Disposition", contentDisposition);
            HttpContext.Response.ContentType = "application/force-download";
            HttpContext.Response.BinaryWrite(System.IO.File.ReadAllBytes(Path.Combine(Server.MapPath("~/Uploads/"), file)));

No comments:

Post a Comment