前台代码如下

@{
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. Egret在Chrome浏览器中的内存占用(内存泄露)

    参考: 怎样查看Chrome的内存占用情况 JS内存泄漏排查方法(Chrome Profiles) chrome内存泄露(一).内存泄漏分析工具 chrome内存泄露(二).内存泄漏实例 目录: 一 ...

  2. PHP 基础知识代码总结

    一.PHP基础语法 变量到数组 <?php //phpinfo(); /* 变量 $a=1;//不分配空间 echo "\$a=".$a; echo "<br ...

  3. angular 路由

    在路由时传递数据 1. 在查询参数中传递数据 /product?id=1&name=2 => ActivatedRoute.queryParams[id] 2.在路由路径中传递数据 {p ...

  4. SharePoint PerformancePoint开发实例

    前言 由于工作的原因,有一段时间没有发新的随笔了,最近使用了SharePoint PerformancePoint做了一些报表,与大家分享经验. 本文完全原创,转载请说明出处,希望对大家有用. 阅读目 ...

  5. 在R语言中封装类读写sql操作工具类

    1.mysql_helper.R # 使用RMySQL操作数据库 # 载入DBI和RMySQL包 library(DBI) library(RMySQL) mysql_con <- functi ...

  6. flask中的blueprint

    https://blog.csdn.net/sunhuaqiang1/article/details/72803336

  7. Appium+python移动端自动化测试-python库及pycharm安装(二)

    一.安装python库 安装python库有很多种方法,如pip安装.源文件安装.运行包安装,但我们最常用的就是使用pip进行安装 Appium+python做移动端的自动化测试,所需要安装以下pyt ...

  8. 使用LoadRunner的Web(HTTP/HTML)协议录制手机app脚本

    一.打开HP Virtual User Generator,创建虚拟用户脚本,选择Web(HTTP/HTML)协议:

  9. golang: multiple http.writeHeader calls

    背景: golang的http服务,读取文件,提供给client下载时候. 出现 multiple http.writeHeader calls 错误. func DownloadFile(w htt ...

  10. Python在运维工作中的经典应用之ansible

    1.安装ansible wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo curl -o /e ...