在ASP.NET MVC中使用Entity Framework将图片上传到SQL Server数据库

问题描述 投票:0回答:1

我一直在尝试使用实体框架将图片上传到 SQL Server 数据库。

我尝试拍摄照片并将其从 DtoModel 中的

IFormFile
转换为主模型中的
byte[]
以将其存储在数据库中,但它不起作用,我得到一个“无效值”。

我在 ASP.NET Web API 中多次使用了这种逻辑方法,并且运行顺利,所以我无法弄清楚我在这里错过了什么。

主要型号:

        [Key]
        public int Id { get; set; }
       
        public string Name { get; set; }
   
        [Required(ErrorMessage = "Photo is required.")]
        public byte[] Pic { get; set; }

        public string PicFromat { get; set; }
 

D 到模型:

    public string Name { get; set; }
    public IFormFile Pics { get; set; }

控制器:

private readonly ApplicationDbContext _context;
private new List<string> _allowedExtenstions = new List<string> { ".jpg", ".png" }; 
private long _maxAllowedPosterSize = 1048576;

public propertiesController(ApplicationDbContext context)
{
    _context = context;
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create( dtoprop model)
{
        if (!ModelState.IsValid)
        {
            return View( model);
        }

        if(!_allowedExtenstions.Contains(Path.GetExtension(model.Pics.FileName.ToLower())))
        {
            ModelState.AddModelError("Pic", "Only .PNG, .JPG images are allowed!");
    
            return View(model);
        }
    
        if (model.Pics.Length > _maxAllowedPosterSize)
        {
            ModelState.AddModelError("Pic", "Poster cannot be more than 1 MB!");
            return View(model);
        }

        using var dataStream = new MemoryStream();

        await model.Pics.CopyToAsync(dataStream);

        var pic = new property
        {
            Name = model.Name,
            Pic = dataStream.ToArray()
        };

        _context.Properties.Add(pic);
        _context.SaveChanges();

        return RedirectToAction("Index");
}

Create.cshtml

@model EshopTest5.Data.dtoprop

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>property</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="PicFromat" class="control-label"></label>
                <input asp-for="PicFromat" class="form-control" />
                <span asp-validation-for="PicFromat" class="text-danger"></span>
            </div>



            <div class="custom-file">
                <input type="file" class="custom-file-input" asp-for="Pic" accept=".png, .jpg" />
                <label class="custom-file-label" asp-for="Pic"></label>
                <span asp-validation-for="Pic" class="text-danger"></span>
            </div>


           

            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>


       
c# sql-server entity-framework asp.net-core-mvc
1个回答
-1
投票

我个人建议您添加客户端验证

_allowedExtenstions
而不仅仅是服务器端验证,这样用户就不会浪费他/她的数据包将表单数据发布到服务器只是为了返回验证错误

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create( dtoprop model)
    {
        if (!ModelState.IsValid)
        {
            return View( model);
        }

        var stream = new MemoryStream();
        model.Pics.File.CopyTo(stream);
        stream.Position = 0;
        var byteData = stream.ToArray();

        var pic = new property
        {
            Name = model.Name,
            Pic = byteData
        };

        _context.Properties.Add(pic);
        _context.SaveChanges();

        return RedirectToAction("Index");
     }

并且您应该将

enctype="multipart/form-data" method="post"
添加到您的 html 表单中。

© www.soinside.com 2019 - 2024. All rights reserved.