How can I save Image file to SQL database with .NET Core and EF

Viewed 164

There is a problem here, the title and description are saving correctly in the SQL database, but it is sending the image file as null. I made some attempts in this way, but I did not get the result I wanted.

How can I print this?

My class:

public class Workplace
{
        [Key]
        [Column("WorkplaceId")]
        public int WorkplaceId { get; set; }

        [NotMapped]
        [Column("WorkplaceThumbnailImage")]
        public byte[]? WorkpaceThumbnailImage { get; set; }

        [Column("WorkplaceTitle")]
        public string? WorkplaceTite { get; set; }

        [Column("WorkplaceExpanation")]
        public string? WorkplaceExplanation { get; set; }
}

Controller post method:

WorkplaceManager workplaceManager = new WorkplaceManager(new EfWorkplaceRepository());

[AllowAnonymous]
[HttpPost]
public IActionResult Index(Workplace p)
{
    Workplace workPlace = new Workplace();
    MemoryStream memoryStream = new MemoryStream();

    foreach (var file in Request.Form.Files)
    {
        p.WorkplaceTite = file.FileName;
        file.CopyTo(memoryStream);

        p.WorkpaceThumbnailImage = memoryStream.ToArray();
    }

    p.WorkpaceThumbnailImage = p.WorkpaceThumbnailImage;
    p.WorkplaceTite = p.WorkplaceTite;
    p.WorkplaceExplanation = p.WorkplaceExplanation;

    workplaceManager.AddWorkplace(p);

    _logger.LogWarning("Success");

    return RedirectToAction("Index", "Home");                    
}

HTML:

@model EntityLayer.Concrete.Workplace;
@using (Html.BeginForm("Workplaces", "Home", FormMethod.Post, new { enctype = "multipart / form - data"}))
{
    <div class="form-group col-md-12">
                        <label for="inputText">Add</label>
                        <input type="File" class="form-control" id="file" name="file1" multiple="multiple"
                               asp-controller="Home" @Html.DisplayFor(model => model.WorkpaceThumbnailImage) method="post"/>
                    </div>
}
2 Answers

...you are using [NotMapped] on the WorkpaceThumbnailImage property, which exludes it from database mapping.
Try removing it.


Edit
Try this other way:

public class Workplace
{
    [Key]
    [Column("WorkplaceId")]
    public int WorkplaceId { get; set; }

    [Column("WorkplaceThumbnailImage")]
    public byte[]? WorkpaceThumbnailImage { get {
        if(this.MyFile is null) 
            return null;
        using var ms = new MemoryStream();
        this.MyFile.CopyTo(ms);
        return ms.ToArray();
    } }

    [NotMapped]
    public IFormFile MyFile { get; set; }

    [Column("WorkplaceTitle")]
    public string? WorkplaceTite { get; set; }

    [Column("WorkplaceExpanation")]
    public string? WorkplaceExplanation { get; set; }
}  

Controller:

WorkplaceManager workplaceManager = new WorkplaceManager(new EfWorkplaceRepository());

[AllowAnonymous]
[HttpPost]
public IActionResult Index([FromForm] Workplace p)
{
    workplaceManager.AddWorkplace(p);

    _logger.LogWarning("Success");

    return RedirectToAction("Index", "Home");                    
}  

View:
(Renamed the id and name attributes to MyFile because it should match the property name of the class)

@model EntityLayer.Concrete.Workplace;
@using (Html.BeginForm("Workplaces", "Index", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="form-group col-md-12">
        <label for="MyFile">Add</label>
        <input type="file" class="form-control" id="MyFile" name="MyFile" />
    </div>
}

My class:

public class Workplace
    {
            [Key]
            [Column("WorkplaceId")]
            public int WorkplaceId { get; set; }
    
            [NotMapped]
            [Column("WorkplaceThumbnailImage")]
            public byte[]? WorkpaceThumbnailImage { get; set; }
    
            [Column("WorkplaceTitle")]
            public string? WorkplaceTite { get; set; }
    
            [Column("WorkplaceExpanation")]
            public string? WorkplaceExplanation { get; set; }
    }

Controler post method:

WorkplaceManager workplaceManager = new WorkplaceManager(new EfWorkplaceRepository());
[AllowAnonymous]
    [HttpPost]
    public async Task<IActionResult> Index(Workplace p)
    {

        Workplace workPlace = new Workplace();
        MemoryStream memoryStream = new MemoryStream();

        foreach (IFormFile file in Request.Form.Files)
        {
            workPlace.WorkplaceTite = file.Name;
            file.CopyToAsync(memoryStream);

            p.WorkplaceThumbnailImage = memoryStream.ToArray();


            workPlace.WorkplaceThumbnailImage = workPlace.WorkplaceThumbnailImage;
            p.WorkplaceTite = p.WorkplaceTite;
            p.WorkplaceExplanation = p.WorkplaceExplanation;
        }
        workplaceManager.AddWorkplace(p);
                
        _logger.LogWarning("Success");

        return RedirectToAction("Index", "Home");
    }

Html:

@model EntityLayer.Concrete.Workplace;
@using (Html.BeginForm("Workplaces", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
    <div class="col-lg-5">
                    <div class="card text-white rounded-3 sm-3">
                        <button class="btn card text-white rounded-3" type="submit" asp-area="" id="create" asp-controller="Home" asp-action="Hairdresser" style="background-color: #5B2480;">Add</button>
                    </div>
                </div>
}

This is how I edited the codes with your suggestions. It works flawlessly. Thanks to those who contributed. I realized that the problem is caused by missing resources and spaces in "BeginForm".

Related