Help in saving image in SQL database MVC 5 and Entity 6.0

-1

hello very good to all I come to you to ask for help that the truth is not how to solve it I created a CRD envisual studio 2013 that uses MVC 5 And entity 6.0 how can I upload an image from my CRUD created with MVC5 and save it in a sql database since I could check that when using entity I changed my attribute that had image to byte [] and now I do not understand how I can upload my image and save it in my database I understand that I have to do a conversation but I do not know how to start I hope a help porfa I would appreciate it a lot there is my model and in entity ps is as type byte

    
asked by Hector Luna 09.09.2017 в 21:49
source

1 answer

0

An image is nothing more than an array of bytes, so Entity Framework makes it that type of property. What you need to do to save the image that the user is trying to upload is to convert your input / file field to an array of bytes.

View

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <label for="file">Upload Image:</label>
    <input type="file" name="file" id="file" style="width: 100%;" />
    <input type="submit" value="Upload" class="submit" />
}

Controller

    public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                byte[] array = ms.GetBuffer();

                var context = new Models.BDEntities();
                context.activofijoes.Add(new Models.activofijo()
                {
                    FotoAF = array,
                });
                context.SaveChanges();
            }

        }

        return RedirectToAction("actionname", "controller");
    }

Additionally, to show your image in the view, I recommend creating a controller that manages the arrangement of images and you return the image:

Controlller

public class ImagesController : Controller
{
    public ActionResult Index(int id)
    {
        var context = new Models.DBEntities();
        byte[] imageData = context.activofijoes.FirstOrDefault(i => i.id == id)?.FotoAF;
        if (imageData != null)
        {
            return File(imageData, "image/png"); // Might need to adjust the content type based on your actual image type
        }
        return null;
    }
}

View

<img src="@Url.Action("Index", "Images", new { id = 1 })" />
    
answered by 11.09.2017 / 22:31
source