简体   繁体   English

使用ASP.NET MVC中的Entity Framework将图片上传到SQL服务器数据库

[英]Upload picture to SQL Server database using Entity Framework in ASP.NET MVC

I have been trying to upload pictures to a SQL Server database by using Entity Framework.我一直在尝试使用实体框架将图片上传到 SQL 服务器数据库。

I tried to take the picture and convert it from IFormFile in the DtoModel to byte[] in the primary model to store it in the database but it doesn't work and I get an "invalid value".我尝试拍摄照片并将其从IFormFile中的 IFormFile 转换为主要 model 中的byte[]以将其存储在数据库中,但它不起作用,我得到一个“无效值”。

I used this logical method in the ASP.NET Web API many times and it's working smoothly, so I can't figure out what I miss here.我在 ASP.NET Web API 中多次使用这种逻辑方法并且它工作顺利,所以我无法弄清楚我在这里错过了什么。

Primary model:初级 model:

        [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; }
 

DtoModel:模型:

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

Controller: Controller:

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");
}

The Create.cshtml : 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>


       

I personally would advice you add a client side validation for _allowedExtenstions not a server side validation so the user does not waste his/her data bundle posting the formdata to the server only to get back a validation error我个人建议您为_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");
     }

and you should add enctype="multipart/form-data" method="post" to your html form.您应该将enctype="multipart/form-data" method="post"添加到您的 html 表单中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用ASP.NET MVC中的Entity Framework将多张图片上传到SQL服务器数据库 - Upload multiple pictures to SQL Server database using Entity Framework in ASP.NET MVC 如何使用ASP.NET MVC中的实体框架在SQL Server中保存业务模型实体 - How to save a business model entity in SQL Server using Entity Framework in ASP.NET MVC ASP.NET MVC with ENTITY FRAMEWORK (SQL SERVER DATABASE) 图像未显示在视图中......错误显示“无法将“字节”转换为“字符串”” - ASP.NET MVC with ENTITY FRAMEWORK (SQL SERVER DATABASE) Image not showing in view ... The error says 'cannot convert "byte" to "string"' 使用ASP.NET MVC4 RAZOR上传图片 - Upload a picture using ASP.NET MVC4 RAZOR C#如何使用ASP.NET MVC中的实体框架将父数据和子数据插入/更新到sql数据库 - C# How to insert/update the parent and child data to the sql database using entity framework in asp.net mvc 如何使用带有Entity Framework的ASP.net MVC4上传/显示图像 - How to upload/display images using ASP.net MVC4 with Entity Framework PopUp 不在 ASP.NET MVC 5 和实体框架中的数据库中发送数据 - PopUp not sending data in database in ASP.NET MVC 5 and Entity Framework ASP.net MVC与Entity Framework重新排序数据库记录 - ASP.net MVC with Entity Framework reordering database records ASP.NET MVC 4实体框架数据库第一个存储库 - ASP.NET MVC 4 Entity Framework Database First Repository 使用 asp.net mvc 4 + Entity Framework 将图像保存到数据库 - Saving images to database with asp.net mvc 4 + Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM