我有一个带有文件上传页面的ASP.NET核心应用程序。以下是查看代码的一部分:
<form asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" id="movie-update-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label>Image</label><br />
<img id="preview-image" src="" style="width:200px; height:120px; object-fit:scale-down">
<input type="file" asp-for="PreviewImageFile" id="preview-image-file" class="preview-image-file" />
<label class="btn btn-primary" for="preview-image-file">Select file</label>
</div>
<div class="form-group">
<label asp-for="Video">Video</label>
<div asp-for="Video" type="file" class="form-control" />
<span asp-validation-for="Video" class="text-danger"></span>
</div>
ViewModel代码:
public class AddUpdateMovieForm
{
public int Id { get; set; }
[Required]
[MaxLength(1024)]
public string Name { get; set; }
public IFormFile PreviewImageFile { get; set; }
public IFormFile Video { get; set; }
}
控制器方法:
[HttpPost]
public async Task<IActionResult> Update([FromForm]AddUpdateMovieForm form)
{
var img = form.PreviewImageFile; //always null
var video = form.Video; // always null
}
当我上传表单时,PreviewImageFile和Video为null。我还试图在没有ViewModel的情况下上传文件,但它仍然是null。我究竟做错了什么?
答案 0 :(得分:2)
您需要使用enctype="multipart/form-data"
作为“文件上传”的表单属性才能正常工作。
<form asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" id="movie-update-form" enctype="multipart/form-data">
</form>