ASP.Net Core MVC上传文件实例
一 创建From表单元素
1.我们在对应的视图文件里(.cshtml)中编写一下代码。asp-action="upload"表示要请求的控制器方法,未指明控制器时默认访问当前文件所对应的控制器,method="post"表明请求方式为post,enctype属性表示以formdata形式提交表单数据。
input标签中的name属性较为重要,一定需要有,在控制器中通过name属性的值获取文件对象,这里的name属性值为upload。
<form asp-action="upload" method="post" enctype="multipart/form-data">
<input type="file" id="upload" name="upload"/>
<button type="submit">提交</button>
</form>
二 创建控制器Action
public IActionResult upload(string upload)
{
//指定文件上传的存储路径,一般情况下统一指定
string FilePath = AppDomain.CurrentDomain.BaseDirectory+"\\UploadFiles\\";
try
{
var file = Request.Form.Files["upload"];
Stream stream = file.OpenReadStream();
//获取后缀名
var arr = file.FileName.Split('.');
string postfix = arr[arr.Length - 1];
//判断存储路径是否存在,如果不存在则创建
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
//创建新文件名
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "." + postfix;
FileStream fileStream = new FileStream(FilePath + "//" + fileName, FileMode.Create, FileAccess.Write);
var bytes = new byte[stream.Length];
// 写入字节数组,流太长时建议循环写入
stream.Read(bytes, 0, (int)stream.Length);
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Close();
//ViewBag.upload = upload;
//返回JSON对象,JsonData为一个ViewModel,大家可根据情况自行定义
JsonData jsonData = new JsonData { Message = "上传完成", Flage = true, State = 200 };
return Json(jsonData);
}
catch (Exception ex)
{
string log = FilePath + "//" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
if (!System.IO.File.Exists(log))
{
System.IO.File.Create(log);
}
System.IO.File.WriteAllText(log, ex.Message);
return NotFound();
}
}