【问题标题】:Failed to upload an image in Asp.Net core在 Asp.Net core 中上传图片失败
【发布时间】:2021-01-02 10:13:27
【问题描述】:

我正在尝试上传单个图像。但问题是当我上传图片时,我发现 null (我已调试)。 这是我的代码:

  [HttpPost]
        public async   Task <IActionResult> Create(Image products, IFormFile image)
        {
           
            if (ModelState.IsValid)
            {
                if (image != null)
                {
                    var name1 = Path.Combine(_he.WebRootPath + "/Images", Path.GetFileName(image.FileName));
                    var stream2 = new FileStream(name1, FileMode.Create);
                   await image.CopyToAsync(stream2);

                    products.ImageC = "Images/" + image.FileName;
                }


                if (image == null)
                {
                    products.ImageC = "Images/NoImageFound.jpg";
                }



                _db.Images.Add(products);
                 _db.SaveChanges();
                return RedirectToAction(nameof(Index));
            }
            return View(products);
        }


_Create.cshtml

<form asp-action="Create" method="post"  enctype="multipart/form-data">
    <div class="p-4 rounded border">
        <div asp-validation-summary="ModelOnly" class="text-danger">

        </div>

        <div class="form-group row">

            <div class="col-5">
                <p class="text-bold mb-2">Image</p>
                <input asp-for="ImageC" class="" type="file" />
            </div>
           
        </div>


        <div class="form-group">
            <input type="submit" class="btn btn-danger form-control" value="Submit" />

        </div>
    </div>
</form>


//Image.cs (Model)

 public class Image
    {
        public int Id { get; set; }
        public string ImageC { get; set; }
    }

当我输入提交按钮时:-

然后我调试了我的代码,发现了这个问题:-

我不明白为什么我发现了这个空引用?我将如何上传我的图片?我还是个初学者,请帮忙。

【问题讨论】:

  • 声明ImageC字段为IFormFile类型,可以去掉Create方法的第二个参数
  • 参数叫image,字段名叫imagec,你觉得是一样的吗?

标签: c# asp.net-mvc asp.net-core asp.net-core-mvc


【解决方案1】:

我假设在 HttpGet 操作中传递给视图的模型是 Image 类的一个空实例,这就是 HttpPost 操作返回的模型。

所以我们可以简单地在类本身中声明一个 IFormFile 属性,然后让引擎用来自 type="file" 控件的数据填充该属性。

此时HttpPost Create方法中不需要IFormFile类型的参数了。

public class Image
{
    public int Id { get; set; }
    public IFormFile ImageC { get; set; }
}

那么 HttpPost Create 方法中所需的所有其他更改都是此更改的结果。

但是,您的视图和数据库似乎具有相同的模型。在这个简单的案例中,您可以继续忘记 ViewModel 的概念,但最好是为了您将来的努力考虑模型和视图模型之间的这种分离。 UI 应该对用于与数据库交互的模型一无所知。
关于这个主题的更多信息可以在这里找到ASP.NET MVC Model vs ViewModel

【讨论】:

    猜你喜欢
    • 2010-10-05
    • 2018-04-21
    • 2018-04-17
    • 2022-06-19
    • 1970-01-01
    • 2014-10-25
    • 2016-04-11
    • 2014-07-22
    • 1970-01-01
    相关资源
    最近更新 更多