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
- @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
- {
- @Html.ValidationSummary();
- <ol>
- <li class="lifile">
- <input type="file" id="fileToUpload" name="file" />
- <span class="field-validation-error" id="spanfile"></span>
- </li>
- </ol>
- <input type="submit" id="btnSubmit" value="Upload" />
- }
Step 2 : Validating the file on client side
- <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
- [HttpPost]
- public ActionResult FileUpload(HttpPostedFileBase file)
- {
- if (ModelState.IsValid)
- {
- if (file == null)
- {
- ModelState.AddModelError("File", "Please Upload Your file");
- }
- else if (file.ContentLength > 0)
- {
- int MaxContentLength = 1024 * 1024 * 3; //3 MB
- string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
- if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
- {
- ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
- }
- else if (file.ContentLength > MaxContentLength)
- {
- ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
- }
- else
- {
- //TO:DO
- var fileName = Path.GetFileName(file.FileName);
- var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
- file.SaveAs(path);
- ModelState.Clear();
- ViewBag.Message = "File uploaded successfully";
- }
- }
- }
- return View();
- }
How it works...
How to upload a file in MVC4的更多相关文章
- axios upload excel file
axios upload excel file https://github.com/axios/axios/issues/1660 https://stackoverflow.com/questio ...
- fetch & form-data & upload & image file
fetch & form-data & upload & image file no need multipart/form-data https://blog.xinshan ...
- jquery ajax发送delete(use in jquery file upload delete file)
环境: jQuery file upload HTML example code <div class="pic-preview"> <div class=&qu ...
- [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 ...
- exjs上传图片异常:com.jspsmart.upload.SmartUploadException: File can't be saved (1120).
错误: 文件名格式不对:未命??.jpg SmartUpload mySmartUpload = new SmartUpload(); com.jspsmart.upload.File myFile ...
- 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/ ...
- 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 ...
- Github Upload Large File 上传超大文件
Github中单个文件的大小限制是100MB,为了能突破这个限制,我们需要使用Git Large File Storage这个工具,参见这个官方帖子,但是按照其给的步骤,博主未能成功上传超大文件,那么 ...
- 【转发】Html5 File Upload with Progress
Html5 File Upload with Progress Posted by Shiv Kumar on 25th September, 2010Senior Sof ...
随机推荐
- 大数据系列修炼-Scala课程03
前言 今天上班看了很多关于前端js,jQuery.bootstrap.js以及springMVC看得迷迷糊糊的,毕竟以前很少去学习前端的技术,所有看得有点困,还好看得比较多,回家后也开始学习关于Sca ...
- 深度-first遍历图--邻接表实现
在这里,邻接表的实现与深度优先遍历图,使用递归. #include<iostream> using namespace std; #define VERTEXNUM 5//结点数 stru ...
- Activity的LaunchMode情景思考
此链接:http://blog.csdn.net/xiaodongrush/article/details/28597855 1. 有哪几种类型?分别有什么用? http://developer.an ...
- Objective-C马路成魔【14-关键C语言功能】
郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. 假设文章对您有所帮助,欢迎给作者捐赠,支持郝萌主.捐赠数额任意,重在心意^_^ 我要捐赠: 点击捐赠 Cocos2d-X源代码下载:点我传送 这里介绍一 ...
- C#5.0新特性
C#5.0新特性 C#5.0最大的新特性,莫过于Async和Parallel. 以往我们为了让用户界面保持相应,我们可以直接使用异步委托或是System.Threading命名空间中的成员,但Syst ...
- java 集装箱 arraylist 用法
1. ArrayList概述: ArrayList 是一个数组队列.相当于 动态数组. 与Java中的数组相比.它的容量能动态增长.它继承于AbstractList.实现了List, RandomAc ...
- addEventListener
addEventListener addEventListener-开始 前面零散地写了些关于 addEventListener 的内容,觉得比较散,有些地方可能也说得不够清楚明白,所以决定以连载的形 ...
- YII编码规范
类名称: 驼峰式 首字母大字 class PointController class PointRatioController 公共成员方法: 驼峰式 首字母小写 public function ge ...
- PS抠出树叶树枝
1.打开PS 2.加载树叶树枝图片 3.双击该图层,来解锁树叶树枝图层 4.通道面板,只留下蓝色 5.顶部菜单 -> 图像 -> 计算 -> 混合为正片叠底,得到一个新Alpha图层 ...
- PHP 15:异常
原文:PHP 15:异常 看完了out_put_fns.php文件,让我们再看看db_fns.php文件.其代码非常简单,如下: ?> 其作用是连接数据库,并返回一个数据库连接.在这里我们 ...