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">
  2. //get file size
  3. function GetFileSize(fileid) {
  4. try
  5. {
  6. var fileSize = 0;
  7. //for IE
  8. if ($.browser.msie)
  9. {
  10. //before making an object of ActiveXObject,
  11. //please make sure ActiveX is enabled in your IE browser
  12. var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
  13. var objFile = objFSO.getFile(filePath);
  14. var fileSize = objFile.size; //size in kb
  15. fileSize = fileSize / 1048576; //size in mb
  16. }
  17. //for FF, Safari, Opeara and Others
  18. else
  19. {
  20. fileSize = $("#" + fileid)[0].files[0].size //size in kb
  21. fileSize = fileSize / 1048576; //size in mb
  22. }
  23. return fileSize;
  24. }
  25. catch (e)
  26. {
  27. alert("Error is :" + e);
  28. }
  29. }
  30. //get file path from client system
  31. function getNameFromPath(strFilepath)
  32. {
  33. var objRE = new RegExp(/([^\/\\]+)$/);
  34. var strName = objRE.exec(strFilepath);
  35. if (strName == null)
  36. {
  37. return null;
  38. }
  39. else
  40. {
  41. return strName[0];
  42. }
  43. }
  44. $("#btnSubmit").live("click", function ()
  45. {
  46. if ($('#fileToUpload').val() == "")
  47. {
  48. $("#spanfile").html("Please upload file");
  49. return false;
  50. }
  51. else
  52. {
  53. return checkfile();
  54. }
  55. });
  56. function checkfile()
  57. {
  58. var file = getNameFromPath($("#fileToUpload").val());
  59. if (file != null)
  60. {
  61. var extension = file.substr((file.lastIndexOf('.') + 1));
  62. // alert(extension);
  63. switch (extension) {
  64. case 'jpg':
  65. case 'png':
  66. case 'gif':
  67. case 'pdf':
  68. flag = true;
  69. break;
  70. default:
  71. flag = false;
  72. }
  73. }
  74. if (flag == false)
  75. {
  76. $("#spanfile").text("You can upload only jpg,png,gif,pdf extension file");
  77. return false;
  78. }
  79. else
  80. {
  81. var size = GetFileSize('fileToUpload');
  82. if (size > 3)
  83. {
  84. $("#spanfile").text("You can upload file up to 3 MB");
  85. return false;
  86. }
  87. else
  88. {
  89. $("#spanfile").text("");
  90. }
  91. }
  92. }
  93. $(function ()
  94. {
  95. $("#fileToUpload").change(function () {
  96. checkfile();});
  97. });
  98. </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...

  

How to upload a file in MVC4的更多相关文章

  1. axios upload excel file

    axios upload excel file https://github.com/axios/axios/issues/1660 https://stackoverflow.com/questio ...

  2. fetch & form-data & upload & image file

    fetch & form-data & upload & image file no need multipart/form-data https://blog.xinshan ...

  3. jquery ajax发送delete(use in jquery file upload delete file)

    环境: jQuery file upload HTML example code <div class="pic-preview"> <div class=&qu ...

  4. [MODx] Solve cannot upload large file

    If you also run into this problem, dont' worry, here is the solution for you. First: In Modx, go &qu ...

  5. exjs上传图片异常:com.jspsmart.upload.SmartUploadException: File can't be saved (1120).

    错误: 文件名格式不对:未命??.jpg SmartUpload mySmartUpload = new SmartUpload(); com.jspsmart.upload.File myFile ...

  6. Upload a file with $.ajax to AWS S3 with a pre-signed url

    转载自:https://gist.github.com/guumaster/9f18204aca2bd6c71a24 生成预签名的Demo文档:https://docs.aws.amazon.com/ ...

  7. jQuery file upload --Multiple File Input Fields in One Form

    The plugin can be applied to a form with multiple file input fields out of the box. The files are se ...

  8. Github Upload Large File 上传超大文件

    Github中单个文件的大小限制是100MB,为了能突破这个限制,我们需要使用Git Large File Storage这个工具,参见这个官方帖子,但是按照其给的步骤,博主未能成功上传超大文件,那么 ...

  9. 【转发】Html5 File Upload with Progress

    Html5 File Upload with Progress               Posted by Shiv Kumar on 25th September, 2010Senior Sof ...

随机推荐

  1. 【软件project】生存期模型(含图)

    为了反映软件生存周期内各个工作应怎样组织,各阶段怎样衔接,须要软件开发模型给出直观图示表达.软件开发模型是软件思想的详细化,是实施在过程模块中的软件开发方法和工具. 以下来介绍开发模型的特点以及他们的 ...

  2. 纠错《COM技术内幕》之ProgID

    近期在看<COM技术内幕>,看到第六章时发现该章节在解释ProgID时有点错误,特此记录一下,也给正在学习COM的小伙伴们一个提示. 并且我发现该问题存在于一些非常多大型软件的COM组件中 ...

  3. linux_UBUNTU 12.04 上使用 SQUID 架设HTTP正向代理服务器

    配置普通HTTP正向代理 安装   1 sudo apt-get install squid squid-common 配置 squid3   1 sudo vim /etc/squid3/squid ...

  4. Myeclipse重装后的必要配置

    一.JDK位置 每台机器同意多个jdk版本号存在,编译时选择须要使用的jdk就可以.MyEclipse->Properties->Java->Installed JRES选择jdk位 ...

  5. C---数组名作函数参数

    数组名可以作函数的实参和形参.如: #include<stdio.h> int main(void) { ]; f(array,); } f(int arr[],int n) { } ar ...

  6. linux c socket programming

    原文:linux c socket programming http://54min.com/post/http-client-examples-using-c.html 好文章 PPT http:/ ...

  7. C语言得到当前系统时间

    void getTime(){ //获取当前系统时间 time_t tTime;//距离1900年1月1日的秒数 char str[80]; struct tm* stTim;//时间结构 time( ...

  8. 【C++ Primer】拷贝控制

    十三.复制控制 1. 复制构造函数 类中的成员函数都默觉得inline类型.所以即使在类定义体内的函数声明显示定义为inline类型,在进行函数定义时也可以将inline进行省略. // 复制构造函数 ...

  9. Django小例子 – 模型数据的模板呈现

    学习Django的这几天,学习过程还是很愉快的,django采用的MVC架构,学习曲线十分平缓,在深入学习之前,先简单的整理记录下django从数据库中获取数据并在模板中使用的方法.温故而知新 ^_^ ...

  10. 三个创建WebStorm项目的方法

    WebStorm项目代表一个完整的解决方案和定义项目范围设置.而重点则是代码完成.代码重构.代码风格等. 因此在建立项目时,WebStorm可以通过三个方面来完成:下载远程项目.复制控制存储库项目和直 ...