ASP.NET MVC上传文件
/// <summary>
/// 批量上传文件
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public ActionResult Upload(HttpPostedFileBase f)
{
//检测年月文件夹是否存在
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month.ToString();
string path = Server.MapPath("~/Upload/" + year + "-" + month);
if (Directory.Exists(path) == false)
{
Directory.CreateDirectory(path);
}
try
{
var files = Request.Files;
if (files.Count == 0)
{
return Json(GetResult(false, "提示:没有要上传的文件!", null));
}
var i = 1;
foreach (string file in files)//file是file文件的name
{
//获取文件信息
var curFile = Request.Files[file];
if (curFile != null && curFile.ContentLength < 1)
{
continue;
}
//获取文件名
var fileName = Path.GetFileName(curFile.FileName);
if (fileName == null)
{
continue;
}
//文件后缀名
var filePostfixName = fileName.Substring(fileName.LastIndexOf('.'));
//新文件名
var newFileName = (DateTime.Now.ToString("yyyyMMddHHmmss") + i) + filePostfixName;
i++;
//拼凑地址
string filename = Path.Combine(path, newFileName);
//保存文件
curFile.SaveAs(filename);
}
return Json(GetResult(true, "上传成功!", null));
}
catch (Exception ex)
{
return Json(GetResult(false, "上传失败,错误信息:" + ex.Message, null));
}
}
版权声明:
作者:亦灵一梦
链接:https://blog.haokaikai.cn/2020/program/aspnet/999.html
来源:开心博客
文章版权归作者所有,未经允许请勿转载。
THE END
1
二维码
海报
ASP.NET MVC上传文件
/// <summary>
/// 批量上传文件
/// </summary>
/// <param name="f"></param>
/// <re……