zoukankan      html  css  js  c++  java
  • 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.  
    31. //get file path from client system
    32. function getNameFromPath(strFilepath)
    33. {
    34. var objRE = new RegExp(/([^/\]+)$/);
    35. var strName = objRE.exec(strFilepath);
    36. if (strName == null)
    37. {
    38. return null;
    39. }
    40. else
    41. {
    42. return strName[0];
    43. }
    44. }
    45.  
    46. $("#btnSubmit").live("click", function ()
    47. {
    48. if ($('#fileToUpload').val() == "")
    49. {
    50. $("#spanfile").html("Please upload file");
    51. return false;
    52. }
    53. else
    54. {
    55. return checkfile();
    56. }
    57. });
    58.  
    59. function checkfile()
    60. {
    61. var file = getNameFromPath($("#fileToUpload").val());
    62. if (file != null)
    63. {
    64. var extension = file.substr((file.lastIndexOf('.') + 1));
    65. // alert(extension);
    66. switch (extension) {
    67. case 'jpg':
    68. case 'png':
    69. case 'gif':
    70. case 'pdf':
    71. flag = true;
    72. break;
    73. default:
    74. flag = false;
    75. }
    76. }
    77. if (flag == false)
    78. {
    79. $("#spanfile").text("You can upload only jpg,png,gif,pdf extension file");
    80. return false;
    81. }
    82. else
    83. {
    84. var size = GetFileSize('fileToUpload');
    85. if (size > 3)
    86. {
    87. $("#spanfile").text("You can upload file up to 3 MB");
    88. return false;
    89. }
    90. else
    91. {
    92. $("#spanfile").text("");
    93. }
    94. }
    95. }
    96.  
    97. $(function ()
    98. {
    99. $("#fileToUpload").change(function () {
    100. checkfile();});
    101. });
    102. </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...

      
  • 相关阅读:
    CNN comprehension
    Gradient Descent
    Various Optimization Algorithms For Training Neural Network
    gerrit workflow
    jenkins job配置脚本化
    Jenkins pipeline jobs隐式传参
    make words counter for image with the help of paddlehub model
    make words counter for image with the help of paddlehub model
    git push and gerrit code review
    image similarity
  • 原文地址:https://www.cnblogs.com/njl041x/p/4148723.html
Copyright © 2011-2022 走看看