C# 如何通过将字符串转换为System.Web.HttpPostedFileBase在db中保存图像
我必须向我的数据库中添加一个图像 我的数据库如下C# 如何通过将字符串转换为System.Web.HttpPostedFileBase在db中保存图像,c#,asp.net-mvc,image-uploading,C#,Asp.net Mvc,Image Uploading,我必须向我的数据库中添加一个图像 我的数据库如下 TableName = Product - PId[int] - PImage[nvarchar(max)] 我正在ASP.NETMVC中使用DB-FIRST方法制作一个应用程序 因此,我的模型类如下(它是自动生成的) 我的用于添加新图像的控制器如下所示。 我这样做是因为我的观点是正确的 public ActionResult Create() { return View(); } [HttpPost] public ActionR
TableName = Product
- PId[int]
- PImage[nvarchar(max)]
我正在ASP.NETMVC中使用DB-FIRST方法制作一个应用程序
因此,我的模型类如下(它是自动生成的)
我的用于添加新图像的控制器如下所示。
我这样做是因为我的观点是正确的
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();
}
我的看法很好
它同时返回PId和PImage
PId正在数据库中保存
问题是我不知道如何在db中保存图像。添加类:
public HttpPostedFileBase Image { get; set; }
然后控制器:
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();
}
我认为这将有助于您不能像这样处理httpposted文件。这有助于:
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();
}