Go to Controllers->HomeController.cs file
a) Add using statement
using
System.IO;
b) Include Action → FileUpload
AcceptVerbs(HttpVerbs.Post)]
public
ActionResult FileUpload(HttpPostedFileBase
uploadFile)
{
if (uploadFile
!= null)
{
if
(uploadFile.ContentLength > 0)
{
string strSuffixFileName
= "_" +
DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss").Replace("_",
"");
string FilePath =
HttpContext.Server.MapPath("../Uploads")
+ "\\ " + strSuffixFileName +
"_" + Path.GetFileName(uploadFile.FileName);
uploadFile.SaveAs(FilePath);
TempData["UploadValidationMessage_Success"]
= "Data Upload Succeeded" + FilePath;
return View("Index");
}
return View("Index");
}
else
{
TempData["UploadValidationMessage_Failure"]
= "Please provide the filename to be uploaded";
return View("Index");
}
}
UploadFile is of type HttpPostedFileBase which Serves as the base class for
classes that provide access to individual files that have been uploaded by a
client.
ContentLength-gets the size of an uploaded file, in bytes.
uploadFile.SaveAs-saves the contents of an uploaded file.
Filename gets prefixed with the current date and time before getting saved
in the folder – Uploads.
Uploads- is the folder we need to create in Server – For testing purpose I
have created it inside the Project folder in my client machine. - It can be
seen if you download the Source Code .
Filename gets prefixed with the current date and time before getting saved
in the folder – Uploads.
I have added 2 validations in the above Action Code-
a) Say if user tries to Upload an empty file – he would get corresponding
Validation message.
b) Say if user doesn't selects a file and tries to upload - he would get
corresponding Validation message.
7. Run the application.
a)
b) Click Browse-> Select the file to be uploaded and click Upload File –
Once File is successfully uploaded in the folder Uploads – We would get the
Success message as in below screen-shot.