.Net Core MVC:尝试上传图像时控制器中出现 NullReferenceException
Posted
技术标签:
【中文标题】.Net Core MVC:尝试上传图像时控制器中出现 NullReferenceException【英文标题】:.Net Core MVC: NullReferenceException in Controller when attempting to upload image 【发布时间】:2021-01-27 13:17:05 【问题描述】:我正在尝试添加一项功能,允许用户上传他们宠物的照片。我是 MVC 新手,正在使用本教程作为指导:https://www.codaffection.com/asp-net-core-article/asp-net-core-mvc-image-upload-and-retrieve/
查看:
@model PetPhotoModel;
@
ViewData["Title"] = "Upload A photo of your pet";
<div class="row">
<div class="col-md-4">
<form asp-action="UploadPhoto">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="PetName" class="control-label"></label>
<input asp-for="PetName" class="form-control" />
<span asp-validation-for="PetName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ImageFile" class="control-label"></label>
<input asp-for="ImageFile" accept="image/*" />
<span asp-validation-for="ImageFile" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="UploadPhoto" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts
@await html.RenderPartialAsync("_ValidationScriptsPartial");
控制器(部分):
...
public IActionResult UploadPhoto()
return View();
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UploadPhoto([Bind("Id,PetName,Title,Description,ImageFile")] PetPhotoModel petPhotoModel)
if (ModelState.IsValid)
//Save image to wwwroot/image
string wwwRootPath = _hostEnvironment.WebRootPath;
string fileName = Path.GetFileNameWithoutExtension(petPhotoModel.ImageFile.FileName);
string extension = Path.GetExtension(petPhotoModel.ImageFile.FileName);
petPhotoModel.ImageName = fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
string path = Path.Combine(wwwRootPath + "/Image/", fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
await petPhotoModel.ImageFile.CopyToAsync(fileStream);
//GetLoggedInUser() gets the current user by id from the db context
GetLoggedInUser().Uploads.Add(petPhotoModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
return View(petPhotoModel);
...
UserModel
包含PetPhotoModel
的集合,以便在数据库中创建一对多关系:
public virtual ICollection<PetPhotoModel> Uploads get; set;
宠物照片模型:
public class PetPhotoModel
private DateTime _dateUploaded = DateTime.Now;
public int Id get; set;
[Required]
public string PetName get; set;
[Required]
public string Title get; set;
public string Description get; set;
[Column(TypeName = "nvarchar(100)")]
[DisplayName("Image Name")]
public string ImageName get; set;
[NotMapped]
[DisplayName("Upload File")]
public IFormFile ImageFile get; set;
public DateTime DateUploaded
get return _dateUploaded;
set _dateUploaded = value;
...
问题是在按下提交按钮后,尽管图像已上传到视图中,但控制器根本没有从视图中获取任何有关图像的数据:
[
【问题讨论】:
我在您的表单中没有看到任何表明它是multipart
的内容,这在传递文件时是必需的。你也可以看看这个相关的帖子:(***.com/questions/46437044/…)。您的表单中也没有与模型属性 ImageName
相关的任何内容
【参考方案1】:
当表单包含任何类型的文件元素时,您必须使用“multipart/form-data”编码。由于默认编码为“application/x-www-form-urlencoded”,请将您视图中的表单标签更改为:
<form asp-action="UploadPhoto" enctype="multipart/form-data" method="post">
【讨论】:
以上是关于.Net Core MVC:尝试上传图像时控制器中出现 NullReferenceException的主要内容,如果未能解决你的问题,请参考以下文章
文件/图像上传后 ASP.NET 3.0 mvc 应用程序崩溃