0

I have to add a image to my database My Database is as follows

TableName = Product
- PId[int] 
- PImage[nvarchar(max)]

I am making an application in ASP.NET MVC using DB FIRST APPROACH so my model class is as follows (which is auto generated)

using System;
using System.Collections.Generic;

public partial class Product
{
    public int PId { get; set; }
    public string PImage { get; set; }
}

My Controller for adding a new image is as follows. I am doing this way because my view is in React

public ActionResult Create()
{
    return View();
}

[HttpPost]
public ActionResult Create(string myData)
{
    var details = Newtonsoft.Json.Linq.JObject.Parse(myData);

    int PId = Convert.ToInt32((string)details["PId"]);
    string PImage = [(string)details["PImage"]];   // An error is coming Cannot implicitly convert type 'System.Web.HttpPostedFileBase' to 'string'

    Product p = new Product() { PId = PId, PImage = PImage };
    db.Products.Add(p);
    db.SaveChanges();

    return View();
}

My view is fine It is returning both PId and PImage PId is being saved in db The problem is i don't know how to save images in db.

Hossein Golshani
  • 1,847
  • 5
  • 16
  • 27
AJam
  • 37
  • 1
  • 10

1 Answers1

1

Adding your class :

 public HttpPostedFileBase Image { get; set; }

then controller :

 var imageFile = ConvertFileInByteArray(model.Image.InputStream, model.Image.ContentLength);

   private byte[] ConvertFileInByteArray(Stream inputStream, int contentLength)
    {
        try
        {
            byte[] file = null;
            using (var binaryReader = new BinaryReader(inputStream))
            {
                file = binaryReader.ReadBytes(contentLength);
            }
            return file;
        }
        catch (Exception e)
        {
            _logger.Error(e);
            Console.Write(e.ToString());
            throw;
        }
    }

    string imageStr = ComputeHash(imageFile);

    private string ComputeHash(byte[] file)
    {
        MD5 md5 = MD5.Create();

        byte[] hashAraay = md5.ComputeHash(file);

        var builder = new StringBuilder();

        foreach (byte b in hashAraay)
        {
            builder.AppendFormat("{0:x2}", b);
        }

        return builder.ToString();
    }
zaman
  • 145
  • 7