文件上传的几个示例分享【推荐】

2020-05-27 18:03:15易采站长站整理

file.SaveAs(Path.Combine(uploadPath, fileNewName));
}
return Content(sbLog.ToString());
}
[HttpPost] public ActionResult B(IEnumerable<HttpPostedFileBase> files)
{
var sbLog = new StringBuilder(string.Empty);
var fileCount = files == null ? 0 : files.Count();
//访问上传文件地址
var path = @"http://localhost:1010/{0}";
//保存文件地址
var uploadPath = @"D:DTTest";
sbLog.AppendFormat("上传文件目录:{0}<br/>", uploadPath);
sbLog.AppendFormat("上传文件量:{0}<br/>", fileCount);
var i = 0;
foreach (var file in files)
{
if (file == null || string.IsNullOrEmpty(file.FileName)) { continue; }

var fileName = file.FileName;
var fileNewName = DateTime.Now.Ticks + fileName;
sbLog.AppendFormat("第:{0}个文件名称:{1}新名称:{2}下载地址:<a href='{3}' target='_blank'>{2}</a><br/>", i + 1, fileName, fileNewName, string.Format(path, fileNewName));
file.SaveAs(Path.Combine(uploadPath, fileNewName));
}
return Content(sbLog.ToString());
}
[HttpPost] public JsonResult C()
{
Thread.Sleep(1000 * 5);
var response = new MoResponse();
var sbLog = new StringBuilder("开始处理...");
try
{
sbLog.AppendFormat("账号:{0}<br/>", Request.Params["userName"]);
sbLog.AppendFormat("密码:{0}<br/>", Request.Params["userPwd"]);
var fileCount = Request.Files.Count;
//访问上传文件地址
var path = @"http://localhost:1010/{0}";
//保存文件地址
var uploadPath = @"D:DTTest";
sbLog.AppendFormat("上传文件目录:{0}<br/>", uploadPath);
sbLog.AppendFormat("上传文件量:{0}<br/>", fileCount);
for (int i = 0; i < fileCount; i++)
{
var file = Request.Files[i];
if (file == null || string.IsNullOrEmpty(file.FileName)) { continue; }
var fileName = file.FileName;
var fileNewName = DateTime.Now.Ticks + fileName;
sbLog.AppendFormat("第:{0}个文件名称:{1}新名称:{2}下载地址:<a href='{3}' target='_blank'>{2}</a><br/>", i + 1, fileName, fileNewName, string.Format(path, fileNewName));
file.SaveAs(Path.Combine(uploadPath, fileNewName));
response.Status = 1;
}
}
catch (Exception ex)
{
sbLog.AppendFormat("异常信息:{0}", ex.Message);
}
finally
{
response.Data = sbLog.ToString();
}
return Json(response);
}
/// <summary>
/// 保存form提交的表单数据
/// </summary>
/// <returns></returns>
[HttpPost] public JsonResult D()
{
var response = new MoResponse();
var sbLog = new StringBuilder(string.Empty);
try
{
//访问上传文件地址
var path = @"http://localhost:1010/{0}";
sbLog.AppendFormat("账号:{0}<br/>", Request.Params["userName"]);