关于MVC 上传文件
前台代码如下
@{
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 上传文件的更多相关文章
- Spring MVC上传文件
Spring MVC上传文件 1.Web.xml中加入 <servlet> <servlet-name>springmvc</servlet-name> <s ...
- MVC上传文件
ASP.NET MVC上传文件是必段撑握的知识.加强训练才是.以前Insus.NET曾使用第三方MyAjaxForm.js :http://www.cnblogs.com/insus/p/378548 ...
- Spring MVC 上传文件
Spring MVC上传文件需要如下步骤: 1.前台页面,form属性 method设置为post,enctype="multipart/form-data" input的typ ...
- asp.net MVC 上传文件 System.Web.HttpException: 超过了最大请求长度
APS.NET MVC 上传文件出现 System.Web.HttpException: 超过了最大请求长度 这个问题 原因是 默认最大上传文件大小为4096,而我提交的文件太大了. 解决方案:修改 ...
- Spring MVC上传文件原理和resolveLazily说明
问题:使用Spring MVC上传大文件,发现从页面提交,到进入后台controller,时间很长.怀疑是文件上传完成后,才进入.由于在HTTP首部自定义了“Token”字段用于权限校验,Token的 ...
- MVC 上传文件并展示
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 最近在做自学MVC,遇到的问题很多,索性一点点总结 ...
- MVC:上传文件
今天写了一个使用MVC上传的DEMO,很简单不超过10行代码.代码如下(关注重点,所以尽量精简掉其他代码): 项目结构
- ASP.NET MVC上传文件----uploadify的使用
课程设计需要实现上传文件模块,本来ASP.NET是有内置的控件,但是ASP.NET MVC没有,所以就有两种方法:自定义和采用第三方插件.由于时间的关系,故采用第三方插件:uploadify. upl ...
- ASP.NET MVC上传文件
最近参考网络资料,学习了ASP.NET MVC如何上传文件.最基本的,没有用jQuery等技术. 1.定义Model public class TestModel { [Displ ...
- 解析Spring MVC上传文件
新建一个普通的maven工程 在pom.xml文件中引入相应的坐标 <?xml version="1.0" encoding="UTF-8"?> & ...
随机推荐
- 文艺青年装B指南
和大龄文艺青年们去凤凰的时候,很难不注意到狭窄小道旁边的文艺小店.有提供焦糖玛奇朵的咖啡店,有兜售梦露赫本明信片和烟雨 凤凰笔记本的店铺,还有复古式的静吧,常驻唱民谣小众歌曲的流浪歌手.我每看 ...
- Java操作文件转码
package downloadTest; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.F ...
- style,currentStyle和getComputedStyle的区别
样式表有三种方式 内嵌样式(inline Style) :是写在Tag里面的,内嵌样式只对所有的Tag有效. 内部样式(internal Style Sheet):是写在HTML的里面的,内部样式只对 ...
- AOP通知无法切入指定方法
AOP通知,切入指定方法时拦截不到,可能是拦截的方法本身是被本类的其他方法调用的,根据AOP反射原理是无法拦截本类中方法调用的方法的.如: class AImpl implements AIf { s ...
- HDU 5701 中位数计数 百度之星初赛
中位数计数 Time Limit: 12000/6000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Total Sub ...
- 演示一个简单的Redis队列
0.Windows Service版下载 https://github.com/rgl/redis/downloads 1.新建一个Console项目 打开Nuget控制台,执行以下命令 Instal ...
- [iOS微博项目 - 4.4] - 会员标识
github: https://github.com/hellovoidworld/HVWWeibo A.会员标识 1.需求 给vip会员打上会员标识 不同等级的vip会员使用不同的标识 使用橙色作为 ...
- timepicker php strtotime 8hours
https://jqueryui.com/datepicker/ w timepicker datepicker 日期 时间 选择器 <script src="static/jquer ...
- Zookeeper简介及使用
一.Zookeeper简介 1.zookeeper简介 动物管理员 Apache ZooKeeper致力于开发和维护开源服务器,实现高度可靠的分布式协调. 2.什么是ZooKeeper? ZooKee ...
- Fibonacci----poj3070(矩阵快速幂, 模板)
题目链接:http://poj.org/problem?id=3070 . 就是斐波那契的另一种表示方法是矩阵的幂: 所以是矩阵快速幂:矩阵快速幂学习 #include <cstdio> ...