前台代码如下

@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<title>Index</title>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script type="text/javascript">
var times = 1;
$("#add").click(function () {
var fileNmae = "FileUpLoad" + n;
$("#divdivfile").append("<input type=\"file\" name=\"" + fileNmae + "\" />");
times++;
});
</script>
</head>
<body>
<div>
@using (Html.BeginForm("UpLoad", "UpdateLoad", FormMethod.Post, new { enctype="multipart/form-data"}))
{
<div id="divfile">
<input type="file" name="FileUpload" />
</div>
<input type="button" id="add" value="增加" />
<input type="submit" id="Submit" value="上传" />
}
</div>
</body>
</html>

首先判断上传的文件是否合法

    public enum FileTypeExtension
{
GIF = ,
PNG = ,
JPG = ,
}
public class FileUploadCommon
{
/// <summary>
/// 主要用于判断上传的特定文件是否附合特定后缀名的限制
/// </summary>
/// <param name="fu">上传的文件对象</param>
/// <param name="fileEx">系统允许上传的文件的类型</param>
/// <returns>true:代表通过验证,false:代表没有通过验证</returns>
public static bool IsAllowedExtension(HttpPostedFileBase fu, FileTypeExtension[] fileEx)
{
int contentLength = fu.ContentLength;
byte[] buffer = new byte[contentLength];
fu.InputStream.Read(buffer, , contentLength);
MemoryStream input = new MemoryStream(buffer);
BinaryReader reader = new BinaryReader(input);
string s = "";
try
{
s = reader.ReadByte().ToString();
s = s + reader.ReadByte().ToString();
}
catch
{
}
reader.Close();
input.Close();
foreach (FileTypeExtension extension in fileEx)
{
if (int.Parse(s) == Convert.ToInt32(extension))
{
return true;
}
}
return false;
} }

后台代码 分为 单个上传和批量上传,注示部份为批量上传

[HttpPost]
[ValidateInput(false)]
public ActionResult UpLoad(FormModel model)
{
FileTypeExtension[] fileTypeArr = { FileTypeExtension.GIF, FileTypeExtension.JPG, FileTypeExtension.PNG };
// 单个上传
try
{
if (Request.Files != null && Request.Files.Count > && Request.Files[].ContentLength > )
{
string fileType = Request.Files[0].FileName.Substring(Request.Files[0].FileName.LastIndexOf(".")); // 获取文件类型
Stream fileStream = Request.Files[].InputStream;
bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[], fileTypeArr); // 判断上传的文件是否合法
if (fileOk && Request.Files[].ContentLength / < ) // 判断合法 及 文件大小是否合法
{
string path = Server.MapPath("/Content/FileUpdateLoad/");
string fileName = Path.GetFileNameWithoutExtension(Request.Files[].FileName) + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType;
Request.Files[].SaveAs(Path.Combine(path, fileName));
return RedirectToAction("Index", "UpdateLoad");
}
else
ViewBag.Error = "文件过大或格式不正确";
}
else
ViewBag.Error = "上传文件失败,可能您未选择上传文件";
}
catch (Exception ex)
{
ViewBag.Error = "上传文件失败,原因如下:" + ex.Message;
}
//foreach (string upload in Request.Files) // 如果是批量上传
//{
// if (upload != null && Request.Files[upload].ContentLength > 0)
// {
// string fileType = Request.Files[upload].ContentType; // 获取文件类型
// Stream fileStream = Request.Files[upload].InputStream;
// bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[upload], fileTypeArr); // 判断上传的文件是否合法
// if (fileOk && Request.Files[upload].ContentLength / 1024 < 1024) // 判断合法 及 文件大小是否合法
// {
// string path = Server.MapPath("/Content/FileUpdateLoad/");
// string fileName = Path.GetFileNameWithoutExtension(Request.Files[upload].FileName) + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType;
// Request.Files[upload].SaveAs(Path.Combine(path, fileName));
// }
// else
// ViewBag.Error = "文件过大或格式不正确";
// }
// else continue;
//}
return View(model);
}

还可以通过以下方式:

  [HttpPost]
[ValidateInput(false)]
public ActionResult UpdateLoad()
{
FileTypeExtension[] fileTypeArr = { FileTypeExtension.GIF, FileTypeExtension.JPG, FileTypeExtension.PNG };
// 单个上传
try
{
if (Request.Files != null && Request.Files.Count > && Request.Files[].ContentLength > )
{
HttpRequest request = System.Web.HttpContext.Current.Request;
HttpFileCollection FileCollect = request.Files;
if (FileCollect.Count > && FileCollect[].ContentLength>) //如果集合的数量大于0
{
//foreach (string str in FileCollect)
//{
// HttpPostedFile FileSave = FileCollect[str]; //用key获取单个文件对象HttpPostedFile
// string imgName = DateTime.Now.ToString("yyyyMMddhhmmss");
// string imgPath = "/" + imgName + FileSave.FileName; //通过此对象获取文件名
// string AbsolutePath = Server.MapPath(imgPath);
// FileSave.SaveAs(AbsolutePath); //将上传的东西保存
// Response.Write("<img src='" + imgPath + "'/>");
//}
HttpPostedFile FileSave = FileCollect[]; //用key获取单个文件对象HttpPostedFile
string fileName = Path.GetFileName(FileSave.FileName);
string imgName = DateTime.Now.ToString("yyyyMMddhhmmss") + FileSave.FileName;
bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[], fileTypeArr); // 判断上传的文件是否合法
if (fileOk && FileSave.ContentLength / < ) // 判断合法 及 文件大小是否合法
{
string AbsolutePath = Server.MapPath("/Content/FileUpdateLoad/" + imgName);
FileSave.SaveAs(AbsolutePath); //将上传的东西保存
//int fileLength = FileSave.ContentLength;
//Byte[] fileByteArr = new Byte[fileLength];
//Stream fileStream = FileSave.InputStream; // 创建文件读取流
//fileStream.Read(fileByteArr, 0, fileLength);
//localhost.WebService1 myService = new localhost.WebService1();
//myService.SaveFile(fileByteArr, fileLength, fileName);
}
}
} }
catch (Exception ex)
{
TempData["UploadError"] = "上传文件失败,原因如下:" + ex.Message;
}
return RedirectToAction("Index");
}

关于配置文件 限制上传文件大小 和上传时间

    <httpRuntime executionTimeout="" maxRequestLength="" useFullyQualifiedRedirectUrl="false"/>
</system.web>

关于MVC 上传文件的更多相关文章

  1. Spring MVC上传文件

    Spring MVC上传文件 1.Web.xml中加入 <servlet> <servlet-name>springmvc</servlet-name> <s ...

  2. MVC上传文件

    ASP.NET MVC上传文件是必段撑握的知识.加强训练才是.以前Insus.NET曾使用第三方MyAjaxForm.js :http://www.cnblogs.com/insus/p/378548 ...

  3. Spring MVC 上传文件

    Spring MVC上传文件需要如下步骤: 1.前台页面,form属性 method设置为post,enctype="multipart/form-data"  input的typ ...

  4. asp.net MVC 上传文件 System.Web.HttpException: 超过了最大请求长度

    APS.NET MVC 上传文件出现  System.Web.HttpException: 超过了最大请求长度 这个问题 原因是 默认最大上传文件大小为4096,而我提交的文件太大了. 解决方案:修改 ...

  5. Spring MVC上传文件原理和resolveLazily说明

    问题:使用Spring MVC上传大文件,发现从页面提交,到进入后台controller,时间很长.怀疑是文件上传完成后,才进入.由于在HTTP首部自定义了“Token”字段用于权限校验,Token的 ...

  6. MVC 上传文件并展示

    最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精    最近在做自学MVC,遇到的问题很多,索性一点点总结 ...

  7. MVC:上传文件

    今天写了一个使用MVC上传的DEMO,很简单不超过10行代码.代码如下(关注重点,所以尽量精简掉其他代码): 项目结构

  8. ASP.NET MVC上传文件----uploadify的使用

    课程设计需要实现上传文件模块,本来ASP.NET是有内置的控件,但是ASP.NET MVC没有,所以就有两种方法:自定义和采用第三方插件.由于时间的关系,故采用第三方插件:uploadify. upl ...

  9. ASP.NET MVC上传文件

    最近参考网络资料,学习了ASP.NET MVC如何上传文件.最基本的,没有用jQuery等技术. 1.定义Model public class TestModel    {        [Displ ...

  10. 解析Spring MVC上传文件

    新建一个普通的maven工程 在pom.xml文件中引入相应的坐标 <?xml version="1.0" encoding="UTF-8"?> & ...

随机推荐

  1. Date 日期格式化

    <span id="time"></span> <script> //名称:日期加法函数 //参数:part(year.month.day.ho ...

  2. 解Bug之路-TCP粘包Bug

    解Bug之路-TCP粘包Bug - 无毁的湖光-Al的个人空间 - 开源中国 https://my.oschina.net/alchemystar/blog/880659 解Bug之路-TCP粘包Bu ...

  3. http请求及json发送与解析 post string

    golang http请求及json流解析 - 长风v持成的博客 - CSDN博客 https://blog.csdn.net/u011677067/article/details/80852158 ...

  4. 全球数字货币交易所TOP20安全性评级报告

      链塔智库2018-05-03 10:28 分析师:常昊.王婧雯    来源: 链塔智库 全球加密数字货币市值超2.5万亿元,单日交易额超2000亿元,全球超过3000万人已投入加密数字货币领域. ...

  5. Linux内核中namespace之PID namespace

    前面看了LInux PCI设备初始化,看得有点晕,就转手整理下之前写的笔记,同时休息一下!!~(@^_^@)~ 这片文章是之前写的,其中参考了某些大牛们的博客!! PID框架的设计 一个框架的设计会考 ...

  6. 前端基础之BOM和DOM和三个小示例(计时器、搜索框、select联动)

    一.BOM和DOM JavaScript分为 ECMAScript,DOM,BOM. BOM(Browser Object Model)是指浏览器对象模型,它使 JavaScript 有能力与浏览器进 ...

  7. LightOJ1003---Drunk(拓扑排序判环)

    One of my friends is always drunk. So, sometimes I get a bit confused whether he is drunk or not. So ...

  8. OCR技术浅探:特征提取(1)

    研究背景 关于光学字符识别(Optical Character Recognition, 下面都简称OCR),是指将图像上的文字转化为计算机可编辑的文字内容,众多的研究人员对相关的技术研究已久,也有不 ...

  9. 9.如何让ubuntu的ssh免密码登录

    ubuntu 默认已安装了 SSH client,此外还需要安装 SSH server: sudo apt-get install openssh-server 安装后,可以使用如下命令登陆本机: s ...

  10. spring 启动过程

    首先,对于一个web应用,其部署在web容器中,web容器提供其一个全局的上下文环境,这个上下文就是ServletContext,其为后面的spring IoC容器提供宿主环境: 其次,在web.xm ...