|
要实现ASP.NET MVC中的多文件上传,其实最关键的一步是要在input上定义multiple属性,使之可以支持多文件上传。
其实有几个比较重要的地方,form一定要申明enctype=“multipart/form-data”,其次是
<input type="file" multiple name="files"/>,表单要有name属性。
好了,前台写好之后,我们就可以选择上传的时候一下子上传多个文件了。
接下来,我们编写后台代码:
在ASP.NET中,我们习惯将一些常量配置到Web.config文件中,然后我们就可以通过读取配置文件访问到,注意的是需要添加System.Configuration.dll
public static Array FilesProcess(string fileType)
{
List<string> list = new List<string>();
var colletion = HttpContext.Current.Request.Files;
string newFileName = string.Empty, fullPath = string.Empty;
string vPath = System.Configuration.ConfigurationManager.AppSettings["UpLoadFilesPath"];
string phyPath = HttpContext.Current.Server.MapPath("/");
try
{
for (int i = 0; i < colletion.Count; i++)
{
HttpPostedFile file = colletion[i];
if (file.ContentType.StartsWith(fileType) == false || file.FileName == "" || file.ContentLength == 0)
{
throw new Exception("上传的文件不允许为空");
//用户并没有上传图片,什么都不做
}
else
{
if (!file.ContentType.StartsWith(fileType))
{
throw new Exception("上传文件的格式不满足要求");
}
string fileName = file.FileName;
string extName = Path.GetExtension(fileName);
newFileName = Guid.NewGuid() + extName;
fullPath = phyPath + vPath + newFileName;
file.SaveAs(fullPath);
list.Add(vPath + newFileName);
}
}
}
catch (Exception ex)
{
list.Clear();
}
return list.ToArray();
} 这是我独自封装的一个上传的处理类,其参数就是文件的mime类型(IIS中可以找到近乎所有的文件的Mine,在C#中调用,其位于“System.Web.MimeMapping”)。
至于为什么要判断filesName和ContentLength,当用户并没有上传文件的时候,其Count也不为零。我们使用Guid重新为文件命名,防止文件冲突,大家可以看出,我这个全部写到了try-catch里面去了,这样其实是不好的,一旦内部发生异常,就是外界无法知道你内部到底发生了什么,所以我们再重载一个方法:
public static Array FilesProcess(string fileType,out string Msg)
{
List<string> list = new List<string>();
var colletion = HttpContext.Current.Request.Files;
string newFileName = string.Empty, fullPath = string.Empty;
string vPath = System.Configuration.ConfigurationManager.AppSettings["UpLoadFilesPath"];
string phyPath = HttpContext.Current.Server.MapPath("/");
try
{
for (int i = 0; i < colletion.Count; i++)
{
HttpPostedFile file = colletion[i];
if (file.ContentType.StartsWith(fileType) == false || file.FileName == "" || file.ContentLength == 0)
{
throw new Exception("上传的文件不允许为空");
//用户并没有上传图片,什么都不做
}
else
{
if (!file.ContentType.StartsWith(fileType))
{
throw new Exception("上传文件的格式不满足要求");
}
string fileName = file.FileName;
string extName = Path.GetExtension(fileName);
newFileName = Guid.NewGuid() + extName;
fullPath = phyPath + vPath + newFileName;
// file.SaveAs(fullPath);
list.Add(vPath + newFileName);
}
}
}
catch (Exception ex)
{
list.Clear();
Msg = ex.Message;
}
Msg = "文件上传成功!";
return list.ToArray();
}
我才疏学浅,仅供大家参考,如有错误,敬请海涵。
|