How to upload a file in MVC4

Uploading a file in Asp.Net MVC application is very easy. The posted file is automatically available as a HttpPostedFileBase parameters in the action of the controler. For uploading a file on the server you required to have a file input control with in html form having encoding type set to multipart/form-data. The default encoding type of a form is application/x-www-form-urlencoded and this is no sufficient for posting a large amount of data to server.

How to do it..

Step 1 : Form for uploading the file

 
 
  1. @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
  2. {
  3. @Html.ValidationSummary();
  4. <ol>
  5. <li class="lifile">
  6. <input type="file" id="fileToUpload" name="file" />
  7. <span class="field-validation-error" id="spanfile"></span>
  8. </li>
  9. </ol>
  10. <input type="submit" id="btnSubmit" value="Upload" />
  11. }

Step 2 : Validating the file on client side

  1. <script type="text/jscript">
    • //get file size
    • function GetFileSize(fileid) {
    • try
    • {
    • var fileSize = 0;
    • //for IE
    • if ($.browser.msie)
    • {
    • //before making an object of ActiveXObject,
    • //please make sure ActiveX is enabled in your IE browser
    • var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
    • var objFile = objFSO.getFile(filePath);
    • var fileSize = objFile.size; //size in kb
    • fileSize = fileSize / 1048576; //size in mb
    • }
    • //for FF, Safari, Opeara and Others
    • else
    • {
    • fileSize = $("#" + fileid)[0].files[0].size //size in kb
    • fileSize = fileSize / 1048576; //size in mb
    • }
    • return fileSize;
    • }
    • catch (e)
    • {
    • alert("Error is :" + e);
    • }
    • }
    •  
    • //get file path from client system
    • function getNameFromPath(strFilepath)
    • {
    • var objRE = new RegExp(/([^\/\\]+)$/);
    • var strName = objRE.exec(strFilepath);
    • if (strName == null)
    • {
    • return null;
    • }
    • else
    • {
    • return strName[0];
    • }
    • }
    •  
    • $("#btnSubmit").live("click", function ()
    • {
    • if ($('#fileToUpload').val() == "")
    • {
    • $("#spanfile").html("Please upload file");
    • return false;
    • }
    • else
    • {
    • return checkfile();
    • }
    • });
    •  
    • function checkfile()
    • {
    • var file = getNameFromPath($("#fileToUpload").val());
    • if (file != null)
    • {
    • var extension = file.substr((file.lastIndexOf('.') + 1));
    • // alert(extension);
    • switch (extension) {
    • case 'jpg':
    • case 'png':
    • case 'gif':
    • case 'pdf':
    • flag = true;
    • break;
    • default:
    • flag = false;
    • }
    • }
    • if (flag == false)
    • {
    • $("#spanfile").text("You can upload only jpg,png,gif,pdf extension file");
    • return false;
    • }
    • else
    • {
    • var size = GetFileSize('fileToUpload');
    • if (size > 3)
    • {
    • $("#spanfile").text("You can upload file up to 3 MB");
    • return false;
    • }
    • else
    • {
    • $("#spanfile").text("");
    • }
    • }
    • }
    •  
    • $(function ()
    • {
    • $("#fileToUpload").change(function () {
    • checkfile();});
    • });
    • </script>

Step 3 : Controller's action for receiving the posted file

  1. [HttpPost]
  2. public ActionResult FileUpload(HttpPostedFileBase file)
  3. {
  4. if (ModelState.IsValid)
  5. {
  6. if (file == null)
  7. {
  8. ModelState.AddModelError("File", "Please Upload Your file");
  9. }
  10. else if (file.ContentLength > 0)
  11. {
  12. int MaxContentLength = 1024 * 1024 * 3; //3 MB
  13. string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
  14. if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
  15. {
  16. ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
  17. }
  18. else if (file.ContentLength > MaxContentLength)
  19. {
  20. ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
  21. }
  22. else
  23. {
  24. //TO:DO
  25. var fileName = Path.GetFileName(file.FileName);
  26. var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
  27. file.SaveAs(path);
  28. ModelState.Clear();
  29. ViewBag.Message = "File uploaded successfully";
  30. }
  31. }
  32. }
  33. return View();
  34. }

How it works...

fileupload.png   fileupload1.png   fileupload2.png

转载于:https://www.cnblogs.com/njl041x/p/4148723.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值