关于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"?> & ...
随机推荐
- [Android Tips] 26. Multiple Maven repositories in Gradle
来自 https://gradleproject.wordpress.com/2013/02/14/multiple-maven-repositories-in-gradle/ This DOESN' ...
- 使用 MySQL 管理层次结构的数据
概述 我们知道,关系数据库的表更适合扁平的列表,而不是像 XML 那样可以直管的保存具有父子关系的层次结构数据. 首先定义一下我们讨论的层次结构,是这样的一组数据,每个条目只能有一个父条目,可以有零个 ...
- C# 构建动态Lambda表达式
做CURD开发的过程中,通常都会需要GetList,然而查询条件是一个可能变化的需求,如何从容对应需求变化呢? 首先,我们来设计一个套路,尝试以最小的工作量完成一次查询条件的需求变更 1.UI收集查询 ...
- MongoDB 聚合结果大小限制
The aggregate command can return either a cursor or store the results in a collection. When returnin ...
- ubuntu android 设备识别 Setting up a Device for Development
参考: http://developer.android.com/tools/device.html lsusb Bus 001 Device 004: ID 18d1:9025 Google I ...
- XAF 如何从Excel复制多个单元格内容到GridView(收藏)
XAF 如何从Excel复制多个单元格内容到GridView 2012年04月11日 ⁄ 综合 ⁄ 共 10998字 ⁄ 字号 小 中 大 ⁄ 评论关闭 how to paste some excel ...
- 搭建SpringbootAdmin监控中心报错A attempt was made to call the method reactor.retry.Retry.retryMax(I)Lreactor/ret)
遇到了同样的错误,转载记录下: 转载自:https://blog.csdn.net/qq_41938882/article/details/85048953 很明显,还没有启动成功就报错了.报错原 ...
- Windows上安装zabbix客户端
1.下载解压 https://www.zabbix.com/downloads/3.4.0/zabbix_agents_3.4.0.win.zip conf目录下放有agent配置文件 bin目录下有 ...
- 3.Github介绍
很多人都知道,Linus在1991年创建了开源的Linux.从此,Linux系统不断发展,已经成为最大的服务器系统软件了.Linus虽然创建了Linux,但Linux的壮大是靠全世界热心的志愿者参与的 ...
- (0.2.5)Mysql安装——RPM方式安装
rpm安装mysql 卸载与安装服务端 一.安装服务端与客户端 #查看RPM包中所有的文件shell> rpm -qpl mysql-community-server-version-dis ...