一、控制器
[HttpPost]
public IActionResult Edit(StudentEditViewModel model)
{
//检查提供的数据是否有效,如果没有通过验证,需要重新编辑学生信息
// 这样用户就可以更正并重新提交编辑表单
if (ModelState.IsValid)
{
Student student = _studentRepository.GetStudent(model.Id);
student.Email = model.Email;
student.Name = model.Name;
student.ClassName = model.ClassName;
if (model.Photos.Count > 0)
{
if (model.ExistingPhotoPath != null)
{
string filePath = Path.Combine(webHostEnvironment.WebRootPath, "images", model.ExistingPhotoPath);
System.IO.File.Delete(filePath);
}
student.PhotoPath = ProcessUploadedFile(model);
}
Student updateStudent = _studentRepository.Update(student);
return RedirectToAction("Index");
}
return View();
}
/// <summary>
/// 将照片保存到指定的路径中,并返回唯一的文件名
/// </summary>
/// <returns></returns>
private string ProcessUploadedFile(StudentCreateViewModel model)
{
string uniqueFileName = null;
if (model.Photos.Count > 0)
{
foreach (var photo in model.Photos)
{
//必须将图像上传到wwwwroot中的images文件夹
//而要获取wwwroot文件夹的路径,我们需要注入ASP.NET Core提供的IWebHostEnvironment
//通过IWebHostEnvironment服务去获取wwwroot文件夹的路径
string unloadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
// 为了确保文件名是唯一的,我们在文件名后附加一个新的GUID值和一个下划线
uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
//路径
string filePath = Path.Combine(unloadsFolder, uniqueFileName);
//因为使用了非托管资源,所以需要手动进行释放
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
//复制到指定位置
photo.CopyTo(fileStream);
}
}
}
return uniqueFileName;
}
二、Model
1.类
代码如下(示例):
public class StudentEditViewModel:StudentCreateViewModel
{
public int Id { get; set; }
public string ExistingPhotoPath { get; set; }
}
public class StudentCreateViewModel
{
[Display(Name = "名字")]
[Required(ErrorMessage = "请输入名字"), MaxLength(50, ErrorMessage = "名字的长度不能超过50个字符")]
public string Name { get; set; }
[Required]
[Display(Name = "班级信息")]
public ClassNameEnum? ClassName { get; set; }
[Required(ErrorMessage = "请输入邮箱地址")]
[Display(Name = "邮箱地址")]
[RegularExpression(@"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$",
ErrorMessage = "邮箱的格式不正确")]
public string Email { get; set; }
[Display(Name="图片")]
public List<IFormFile> Photos { get; set; }
}
2.视图
代码如下(示例):
@model StudentEditViewModel
@{
ViewBag.Title = "编辑学生信息";
//获取当前学生照片信息路径
var photoPath = "~/images/" + (Model.ExistingPhotoPath ?? "1.jpg");
}
<form enctype="multipart/form-data" asp-controller="home" asp-action="edit" method="post" class="mt-3">
<div asp-validation-summary="All" class="text-danger"></div>
<input hidden asp-for="Id" />
<input hidden asp-for="ExistingPhotoPath" />
<div class="form-group row">
<label asp-for="Name" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Name" class="form-control" placeholder="请输入名字" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Email" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Email" class="form-control" placeholder="请输入邮箱" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="ClassName" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<select asp-for="ClassName" asp-items="Html.GetEnumSelectList<ClassNameEnum>()" class="custom-select mr-sm-2">
<option value="">请选择</option>
</select>
<span asp-validation-for="ClassName" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Photos" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input asp-for="Photos" multiple class="form-control custom-file-input" />
<label class="custom-file-label">请选择照片......</label>
</div>
</div>
</div>
<div class="form-group row col-sm-4 offset-4">
<img class="imagesThumbnail" src="@photoPath" asp-append-version="true" />
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">更新</button>
<a asp-action="index" asp-controller="home" class="btn btn-primary">取消</a>
</div>
</div>
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$('.custom-file-input').on("change", function () {
console.log($(this))
//var fileName = $(this).val().split("\\").pop();
//$(this).next(".custom-file-label").html(fileName);
var fileLable = $(this).next(".custom-file-label");
var files = $(this)[0].files;
if (files.length > 1) {
fileLable.html("您已经选择了" + files.length + "个文件");
} else {
fileLable.html(files[0].name);
}
});
})
</script>
}
</form>
总结
HttpGet没有写出来,多张图片上传