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 pagepublic 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 namefileName += 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();
}