.NET MVC 文件上传

/// 
/// 单文件上传
/// 
/// 
/// 
[HttpPost]
public ActionResult Upload(HttpPostedFileBase files)
{
    try
    {
        if (files == null)
        {
            return Content("请选择上传文件");
        }
        var path = Server.MapPath("../Upload");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
    	string saveUrl = string.Empty;
        string fileName = string.Empty;
        string suffix = string.Empty;
        fileName = files.FileName;
        suffix = fileName.Substring(fileName.LastIndexOf('.'));
        string fname = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
        fileName = fname + suffix;
        saveUrl = Path.Combine(path, fileName);
        files.SaveAs(saveUrl);
        return Content("上传成功");
    }
    catch/*(Exception ex)*/
    {
        throw;
    }
    finally
    {
        
    }
}
/// 
/// 批量上传
/// 
/// 
/// 
[HttpPost]
public ActionResult Uploads(HttpPostedFileBase[] files)
{
    try
    {
        if (files.Length < 1)
        {
            return Content("请选择文件");
        }
        var path = Server.MapPath("../Upload");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
    	string saveUrl = string.Empty;
        string fileName = string.Empty;
        string suffix = string.Empty;
        List<string> list = new List<string>();
        foreach (HttpPostedFileBase item in files)
        {
            fileName = item.FileName;
            suffix = fileName.Substring(fileName.LastIndexOf('.'));
            string fname = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
            fileName = fname + suffix;
            saveUrl = Path.Combine(path, fileName);
            item.SaveAs(saveUrl);
            list.Add(saveUrl);
        }
        return Content("上传成功");
    }
    catch/*(Exception ex)*/
    {
        throw;
    }
    finally
    {
        
    }
}

你可能感兴趣的:(NET,文件上传)