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">
  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...

  

时间: 2024-10-23 15:23:09

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

ubuntu下vagrant up经常出现Failed to upload a file to the guest VM via SCP due to a permissions error.最终解决

? /vagrant vagrant reload [default] Attempting graceful shutdown of VM... [default] Clearing any previously set forwarded ports... [default] Clearing any previously set network interfaces... [default] Preparing network interfaces based on configurati

jspsmartupload上传出现com.jspsmart.upload.SmartUploadException: File can&#39;t be saved (1120).

出现这个错误的原因可能是自己访问地址的ip有问题 输出你的ip地址看看是不是0.0.0.0.0.0.0.1这个是ipv6表示的本机地址对应的ipv4就是127.0.0.1. 这个地址在重命名文件的时候会出现错误所以我们可以将其改成其他的ip地址 可以尝试换成自己局域网的ip地址或是自己的本机的ip地址即路径 不再是http://localhost:8080/myupload/myupload.jsp而是 http://192.168.1.6:8080/myupload/myupload.jsp

file upload download

1. 文件上传与下载 1.1 文件上传 案例: 注册表单/保存商品等相关模块! --à 注册选择头像 / 商品图片 (数据库:存储图片路径 / 图片保存到服务器中指定的目录) 文件上传,要点: 前台: 1. 提交方式:post 2. 表单中有文件上传的表单项: <input type="file" /> 3. 指定表单类型: 默认类型:enctype="application/x-www-form-urlencoded" 文件上传类型:multipart

Upload file

<h3>Upload File</h3> <form action="@Url.Action("Upload","UploadController")" method="post" id="uploadForm" enctype="multipart/form-data"> <div class="file-box">

RFC1867 HTTP file upload

RFC1867 is the standard definition of that "Browse..." button that you use to upload files to a Web server. It introduced the INPUT field type="file", which is that button, and also specified a multipart form encoding which is capable

Web for pentester_writeup之File Upload篇

Web for pentester_writeup之File Upload篇 File Upload(文件上传) Example 1 直接上传一句话木马,使用蚁剑连接 成功连接,获取网站根目录 Example 2 可以看到上传文件做了相关限制,不允许上传PHP文件, 修改后缀名为linux不识别的xxx,上传 同样成功连接,我们还可以修改后缀名为.php3,有些系统.php4,.php5也能成功执行 文件上传绕过方式有很多,包含 前台脚本检测扩展名绕过 Content-Type检测文件类型绕过

How to Upload Long Text into SAP Using Excel Sheet and SAVE_TEXT Function Module

https://wiki.scn.sap.com/wiki/display/ABAP/How+to+Upload+Long+Text+into+SAP+Using+Excel+Sheet+and+SAVE_TEXT+Function+Module Created by Smruti Ranjan Mohanty, last modified on Oct 09, 2013 Go to start of metadata Reference Link: Note 933420 - ALSM_EXC

PHP-表单的读写,File文件的操作等---ShinePans

实践一: 表单的操作: wlcome_page.php <html> <body> <?php include("menu1.php"); ?> <form action="welcome_info.php" method="post"> <br/> Name         :<input type="text" name="name"/&

Spring multipart file上传

org.springframework.web.multipart.MultipartFile接口 interface MultipartFile { public byte[] getBytes(); public String getContentType(); public java.io.InputStream getInputStream(); public String getName(); public String getOriginalFilename(); public lo