ASP.NET MVC实现批量文件上传实现批量文件上传
主要为大家详细介绍了ASP.NET MVC实现批量文件上传,简单介绍单文件上传的实现方法,具有一定的参考价
值,感兴趣的小伙伴们可以参考一下
根据项目需要,研究了一下如何在ASP.NETMVC下实现批量文件上传。首先,介绍单文件上传;然后,介绍多文件上传如何
实现。
一、单文件上传一、单文件上传
单文件上传的原理是将文件数据放入request中,由页面直接传递至后台controller中,类似于view和controller之间传参数,直
接贴上代码加注释。
Upload.aspx文件中的代码:
<form enctype="multipart/form-data" method="post">
<input type="file" id="file" />
<input type="submit" value="上传" />
</form>
Controller中代码:
[HttpPost]
public ActionResult Upload(FormCollection form)
{
if (Request.Files.Count == 0){
//Request.Files.Count 文件数为0上传不成功
return View();
}
var file = Request.Files[0];
if (file.ContentLength == 0){
//文件大小大(以字节为单位)为0时,做一些操作
return View();
}
else{
//文件大小不为0
file = Request.Files[0]; //服务器上的UpLoadFile文件夹必须有读写权限
string target = Server.MapPath("/")+("/Mock/Learning/");//取得目标文件夹的路径
string filename = file.FileName;//取得文件名字
string path = target + filename;//获取存储的目标地址
file.SaveAs(path);}
return View();
}
这里需要注意的是,在ASP.NET中,request的默认大小为4M,因此,如需上传较大文件,需要更改Web.config。
<system.web>
<httpRuntime maxRequestLength="40960"/>
</system.web>
二、批量文件上传二、批量文件上传
思路是通过js根据用户需求动态添加上传控件,多个文件通过request一并上传至controller。
Upload.aspx文件中的代码:
<form enctype="multipart/form-data" method="post">
<div id="FileList">
<div>
<input type="file" id="file" name="file0"/>
</div>
</div>
<p>
<a onclick="AddFile();">添加文件</a>
</p>
<p>
<input type="submit" value="上传" />
</p>
</form>
<script>
var index = 1;
function AddFile() {
var ul = document.getElementById("FileList");
var inputDiv = document.createElement("div");
inputDiv.setAttribute("Id", "div" + index);
var file = document.createElement("input");
评论0