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 ...
随机推荐
- 【软件project】生存期模型(含图)
为了反映软件生存周期内各个工作应怎样组织,各阶段怎样衔接,须要软件开发模型给出直观图示表达.软件开发模型是软件思想的详细化,是实施在过程模块中的软件开发方法和工具. 以下来介绍开发模型的特点以及他们的 ...
- 纠错《COM技术内幕》之ProgID
近期在看<COM技术内幕>,看到第六章时发现该章节在解释ProgID时有点错误,特此记录一下,也给正在学习COM的小伙伴们一个提示. 并且我发现该问题存在于一些非常多大型软件的COM组件中 ...
- linux_UBUNTU 12.04 上使用 SQUID 架设HTTP正向代理服务器
配置普通HTTP正向代理 安装 1 sudo apt-get install squid squid-common 配置 squid3 1 sudo vim /etc/squid3/squid ...
- Myeclipse重装后的必要配置
一.JDK位置 每台机器同意多个jdk版本号存在,编译时选择须要使用的jdk就可以.MyEclipse->Properties->Java->Installed JRES选择jdk位 ...
- C---数组名作函数参数
数组名可以作函数的实参和形参.如: #include<stdio.h> int main(void) { ]; f(array,); } f(int arr[],int n) { } ar ...
- linux c socket programming
原文:linux c socket programming http://54min.com/post/http-client-examples-using-c.html 好文章 PPT http:/ ...
- C语言得到当前系统时间
void getTime(){ //获取当前系统时间 time_t tTime;//距离1900年1月1日的秒数 char str[80]; struct tm* stTim;//时间结构 time( ...
- 【C++ Primer】拷贝控制
十三.复制控制 1. 复制构造函数 类中的成员函数都默觉得inline类型.所以即使在类定义体内的函数声明显示定义为inline类型,在进行函数定义时也可以将inline进行省略. // 复制构造函数 ...
- Django小例子 – 模型数据的模板呈现
学习Django的这几天,学习过程还是很愉快的,django采用的MVC架构,学习曲线十分平缓,在深入学习之前,先简单的整理记录下django从数据库中获取数据并在模板中使用的方法.温故而知新 ^_^ ...
- 三个创建WebStorm项目的方法
WebStorm项目代表一个完整的解决方案和定义项目范围设置.而重点则是代码完成.代码重构.代码风格等. 因此在建立项目时,WebStorm可以通过三个方面来完成:下载远程项目.复制控制存储库项目和直 ...