[英]How to save posted image in asp.net?
I try in different to save picture Type String
on my database but it always gives me System.Web.HttpPostedFileWrapper
. 我尝试使用其他方法将图片类型
String
保存在数据库中,但它始终为我提供System.Web.HttpPostedFileWrapper
。 I dont understand what's wrong here 我不明白这是怎么了
I want to create a new Product containing title,description, image ,and their category. 我想创建一个包含标题,描述, 图像及其类别的新产品。 When I post data via create it saves data but does not display image and when I check database picture field I find value of image is
HttpPostedFileWrapper
not p.png or product.jpg – 当我通过创建发布数据时,它保存数据但不显示图像,并且当我检查数据库图片字段时,我发现图像的值为
HttpPostedFileWrapper
而不是p.png或product.jpg –
This is controller: 这是控制器:
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Create")]
public ActionResult Create([Bind(Include = "Ida,description,image,Userid,Idc,titre")] Article article,HttpPostedFileBase postedFile)
{
if (ModelState.IsValid)
{
if (postedFile != null)
{
var a =new byte[postedFile.ContentLength] ;
article.image = Convert.ToBase64String(a);
postedFile.InputStream.Read(a, 0, postedFile.ContentLength);
}
db = new IdentityDBEntities2();
// Add article to database
article.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
article.Idc = Convert.ToInt32(Request["Idc"]);
db.Articles.Add(article);
ViewBag.Idcc = new SelectList(db.Categories, "Id", "libelle");
db.SaveChanges();
return RedirectToAction("Index");
}
return View(article);
}
Please change to this, move line of code reading from stream up 请更改为此,将代码行从流中向上移动
if (postedFile != null)
{
var a = new byte[postedFile.ContentLength];
postedFile.InputStream.Read(a, 0, postedFile.ContentLength);
article.image = Convert.ToBase64String(a);
}
Updated: 更新:
I tried to reproduce source code in my side, it worked well. 我试图重现自己的源代码,它运行良好。
Did you setup new {enctype="multipart/form-data"}
for your form? 您是否为表单设置了
new {enctype="multipart/form-data"}
?
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Ida,description,image,Userid,Idc,titre")] Article article, HttpPostedFileBase postedFile)
{
if (ModelState.IsValid)
{
if (postedFile != null)
{
var a = new byte[postedFile.ContentLength];
postedFile.InputStream.Read(a, 0, postedFile.ContentLength);
article.image = Convert.ToBase64String(a);
//db = new IdentityDBEntities2();
//// Add article to database
//article.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
//article.Idc = Convert.ToInt32(Request["Idc"]);
//db.Articles.Add(article);
//ViewBag.Idcc = new SelectList(db.Categories, "Id", "libelle");
//db.SaveChanges();
TempData["Image"] = article.image;
}
return RedirectToAction("Index");
}
return View(article);
}
Create.cshtml file Create.cshtml文件
@using(Html.BeginForm("Create","Feedback",FormMethod.Post,new {enctype="multipart/form-data"}))
{
<input type="file" name="postedFile"/>
<input type="submit" value="Save"/>
}
Index.cshtml file Index.cshtml文件
@{
var imgSrc = string.Format("data:image/gif;base64,{0}", TempData["Image"]);
}
<img src="@imgSrc"/>
You want just to copy a file? 您只想复制一个文件? Why not use:
为什么不使用:
System.IO.File.Copy("source", "destination");
http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx
Your postedfile parameter is a HttpPostedFileBase -type parameter. 您的postedfile参数是HttpPostedFileBase -type参数。 You must save the fully qualified name of the file on the client instead of saving this parameter directly.
您必须在客户端上保存文件的标准名称,而不是直接保存此参数。 Try this:
尝试这个:
article.image = postedFile.FileName;
Just an update. 只是一个更新。 I used varbinary in the end.
最后我使用了varbinary。 I added the image to the database by using
我通过使用将图像添加到数据库
if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".png")
{
Stream stream = postedFile.InputStream;
BinaryReader reader = new BinaryReader(stream);
byte[] imgByte = reader.ReadBytes((int)stream.Length);
con = new SqlConnection("MyConnectionString");
SqlCommand cmd = new SqlCommand("insert into Events (AspNetUsersId,EvtName,EvtType,EvtDescription,EvtDate,EvtVote, EvtImage) values (@AspNetUsersId, @EvtName, @EvtType, @EvtDescription, @EvtDate, @EvtVote, @EvtImage)", con);
cmd.Parameters.AddWithValue("@AspNetUsersId", userId);
cmd.Parameters.AddWithValue("@EvtName", eventName.Text);
cmd.Parameters.AddWithValue("@EvtType", eventType.Text);
cmd.Parameters.AddWithValue("@EvtDescription", eventDescription.Text);
cmd.Parameters.AddWithValue("@EvtDate", datetimepicker.Value);
cmd.Parameters.AddWithValue("@EvtVote", 0);
cmd.Parameters.Add("@EvtImage", SqlDbType.VarBinary).Value = imgByte;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
And displayed it in an image tag by using 并通过使用将其显示在图像标签中
byte[] imgByte = null;
con = new SqlConnection("MyConnectionString");
SqlCommand cmd = new SqlCommand("SELECT * FROM Events", con);
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
imgByte = (byte[])(dr["EvtImage"]);
string str = Convert.ToBase64String(imgByte);
imageTest.Src = "data:Image/png;base64," + str;
}
Front-End code: 前端代码:
<img runat="server" id="imageTest" src="imageIDtagName" />
Thanks for everyone's help ! 谢谢大家的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.