如何在ASP.NET CORE 2中的更新中处理空文件上载

时间:2018-06-08 06:53:03

标签: asp.net asp.net-mvc razor asp.net-core

我有一个Edit form和一个文件上传,如果上传文件有文件,一切正常,但当它为空时,它会将null值传递给数据库。我使用if来检查文件上传长度,但它不起作用。我还从LogoFile删除了Bind。 这是我的.cshtml代码:

<form asp-action="Edit" enctype="multipart/form-data">
<div class="form-group">
                <label asp-for="FirstName" class="control-label"></label>
                <input asp-for="FirstName" class="form-control" />
                <span asp-validation-for="FirstName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="LastName" class="control-label"></label>
                <input asp-for="LastName" class="form-control" />
                <span asp-validation-for="LastName" class="text-danger"></span>
            </div>
<div class="form-group">
                <label asp-for="LogoFile" class="control-label"></label><br />
                <input asp-for="LogoFile" type="file" class="form-control" />
                <img src="/@Html.DisplayFor(model => model.LogoFile)"/>
                <span asp-validation-for="LogoFile" class="text-danger"></span>
            </div>
 <div class="form-group">
                <input type="submit" value="save" class="btn btn-green" />
            </div>
        </form>

这是我的控制器代码:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,FirstName,LastName")] Profile profile,IFormFile LogoFile)
    {

        if (id != profile.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                if (LogoFile != null || LogoFile.Length != 0)

                {
                    var path = "images/" + LogoFile.FileName;

                    using (var stream = new FileStream("wwwroot/" + path, FileMode.Create))
                    {
                        await LogoFile.CopyToAsync(stream);
                        profile.LogoFile = path.ToString();
                    }
                }
                _context.Update(profile);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProfileExists(profile.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(profile);
    }

0 个答案:

没有答案