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 ...
随机推荐
- decimal system 2016
Problem Description As we know , we always use the decimal system in our common life, even using the ...
- linux_增加用户组_删除用户
添加账号组 /usr/sbin/groupadd iknow 添加账号 /usr/sbin/useradd -g iknow -d /home/iknow/ iknow 更改密码 passwd 选项 ...
- 中英文url解码vc++源程序
本文主要讨论中文url解码实现问题,没有具体解说url编码,utf-8编码.想对编解码问题有更加具体的了解,请查阅相关文档 url编码:实质字符ascii码的十六进制.仅仅是略微有些变动,须要在前面加 ...
- 今天才知道css hack是什么
先来个冷笑话:一晚下班回家,一民警迎面巡逻而来.突然对我大喊:站住! 民警:int类型占几个字节? 我:4个. 民警:你可以走了. 我感到很诧异. 我:为什么问这样的问题? 民警:深夜还在街上走,寒酸 ...
- shell的定义
shell一些符号区别对待不同的定义.主要的定义3途径: (1)单引號 (2)双引號 (3)反引號 我们最经常使用的就是双引號和单引號.对于这2个符号,用$变量能够非常清楚的说明它们的差别,例如以下: ...
- MVC+MQ+WinServices+Lucene.Net
MVC+MQ+WinServices+Lucene.Net Demo 前言: 我之前没有接触过Lucene.Net相关的知识,最近在园子里看到很多大神在分享这块的内容,深受启发.秉着“实践出真知”的精 ...
- HDU 4052 Adding New Machine(矩形面积并)
Adding New Machine Problem Description Incredible Crazily Progressing Company (ICPC) suffered a lot ...
- WinForm播放视频
原文:WinForm播放视频 1背景 这几天一老友要求我做个小软件,在WinForm播放视频.印象中微软有个WM控件直接可以使用,晚上研究下 2实现方式 2.1微软草根 最简单的方式,是直接使用微软的 ...
- 皴EBS R12应用程序和数据库用户password
1.假设你有一个EBS周围环境APPS用户password,能够打破用户的应用程序password 参考:Oracle EBS R12下怎样破解用户password 2,假设没有APPS用户passw ...
- itext之pdf导出添加水印Java工具类
import java.io.IOException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentExce ...