如何在asp.net中保存发布的图片?

时间:2019-03-07 10:36:27

标签: asp.net asp.net-mvc entity-framework

我尝试用其他方法将图片类型String保存在数据库中,但它总是给我System.Web.HttpPostedFileWrapper。我不明白这里出了什么问题

我想创建一个包含标题,描述,图像及其类别的新产品。当我通过创建发布数据时,它保存数据但不显示 image ,当我检查数据库图片字段时,我发现图像的值为HttpPostedFileWrapper而不是p.png或product.jpg –

这是控制者:

[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);
}

4 个答案:

答案 0 :(得分:0)

您只想复制文件?为什么不使用:

System.IO.File.Copy("source", "destination");

http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx

答案 1 :(得分:0)

请更改为此,向上移动流中读取的代码行

 if (postedFile != null)
                {
                    var a = new byte[postedFile.ContentLength];
                    postedFile.InputStream.Read(a, 0, postedFile.ContentLength);
                    article.image = Convert.ToBase64String(a);

                }

已更新:

我尝试在自己的身边复制源代码,效果很好。

您是否为表单设置了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文件

@using(Html.BeginForm("Create","Feedback",FormMethod.Post,new {enctype="multipart/form-data"}))
{

    <input type="file" name="postedFile"/>

    <input type="submit" value="Save"/>
}

Index.cshtml文件

@{
    var imgSrc = string.Format("data:image/gif;base64,{0}", TempData["Image"]);
}
<img src="@imgSrc"/>

答案 2 :(得分:0)

您的 postedfile 参数是 HttpPostedFileBase 类型的参数。您必须在客户端上保存文件的标准名称,而不是直接保存此参数。试试这个:

article.image = postedFile.FileName;

答案 3 :(得分:0)

只是一个更新。最后我使用了varbinary。我使用

将图像添加到数据库中
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();
        }

并使用

将其显示在图像标签中
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;
        }

前端代码:

<img runat="server" id="imageTest" src="imageIDtagName" />

感谢大家的帮助!