C# MVC 4 File Upload
Oh dear, let’s just get started. How to create an application that handling Upload file in C# MVC4 .. Okay Get them Tiger!.
1’stCreate the Controller Procedure, like bellow.
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase fileToUpload)
{
string FileName = "";
if (fileToUpload != null && fileToUpload.ContentLength > 0)
try
{
FileName = fileToUpload.FileName;
string path = Path.Combine(Server.MapPath("~/UploadFiles/ITHWSWRequestForm"), Path.GetFileName(FileName));
fileToUpload.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
return View();
}
Now for the explanation of the Controller Code.
[HttpPost]
That word tell us that these function is handling a POST Method data that Posted from View.
public ActionResult FileUpload(HttpPostedFileBase fileToUpload)
The name of the Function “FileUpload” and HttpPostedFile Base is the type parameter that posted from View with ID or variable name “fileToUpload”.
string path = Path.Combine(Server.MapPath("~/UploadFiles/ITHWSWRequestForm"), Path.GetFileName(FileName));
These is the path that directed the location of file that will be stored in the server in here we use "~/UploadFiles/ITHWSWRequestForm" to store the file and Path.GetFileName(FileName) for the file name that will be stored in the server.
fileToUpload.SaveAs(path);
These the method that will save the files.
2’ndAnd for The View.
That handling display and file select we can create Form like these:
<form name="formUpload" id="formUpload" method="post" class="easyui-form" enctype="multipart/form-data">
<table border="0" style="padding:10px; width:100%">
<td>SelectFormFile</td>
<td>
<input id="fileToUpload" name="fileToUpload" size="12" class="easyui-filebox" >
</td>
</tr>
</table>
<a href="#" onclick="uploadthefile()">uploadFile</a>
</form>
Just don’t forgot to implement enctype="multipart/form-data" in form tag.
And the input id for file upload is the same name for variable that will be handle in Controller with type HttpPostedFile .
And now .
3’rdThe Java Script
function uploadthefile() {
$('#formUpload').form('submit', {
url: '/InVRequest/FileUpload',
success: function () {
alert(‘Upload success’);
return true;
},
error: function () {
alert(‘upload failed’);
return;
}
});
}
Okay that all guys.. Just try it.. And good luck..