.net 上传文件
Controller层接收文件 参数 [FromServices] IHostingEnvironment env
public IActionResult UploadFile([FromServices] IHostingEnvironment env)
{
var result = new APIResult<int>();
try
{
var file = HttpContext.Request.Form.Files[0];
_documentService.UploadFiles(env, file);
}
catch (Exception)
{
result.ReturnCode = ReturnCode.SysException;
result.Message = "系统错误";
}
return Json(result);
}
用一个变量File接收文件信息
var file = HttpContext.Request.Form.Files[0];
public void UploadFiles(IHostingEnvironment env, IFormFile file)
{
var filePath = env.WebRootPath; //获取路径
var fileName = file.FileName; //获取文件名称
var ext = Path.GetExtension(file.FileName); //获取上传文件后缀名
var url = filePath + @"\UploadDocuments\";
if (!Directory.Exists(url)) //(字符串存在路径)确定给定路径是否引用磁盘上的现有目录。
{
Directory.CreateDirectory(url); //创建指定路径中的所有目录和子目录,除非它们已经存在。
}
var path = filePath + @"\UploadDocuments\" + DateTime.UtcNow.ToString("yyyyMMddhhmmssfff") + ext;using (var fStream = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite)) //添加文件成功
{
//File.Delete(PathName); //删除指定目录文件
}
}
}