【问题标题】:How to save posted image in asp.net?如何在asp.net中保存发布的图像?
【发布时间】:2019-03-07 10:36:27
【问题描述】:

我尝试在我的数据库中保存图片类型String,但它总是给我System.Web.HttpPostedFileWrapper。我不明白这里有什么问题

我想创建一个包含标题、描述、图片及其类别的新产品。当我通过 create 发布数据时,它会保存数据但不显示 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);
}

【问题讨论】:

  • 请尝试详细说明您的问题。什么是“图片”?你到底想做什么?另请注意,article.image 始终是转换为字符串的空字节数组或其默认值。
  • 你好图片是数据库中的图片,我想在 ~/Content/img 文件夹中显示图片。
  • 如果您的“编辑”是可行的解决方案,请将其移至下面的答案。这有助于更清楚地说明文本的哪一部分是问题,哪一部分是自我回答。
  • 好的兄弟,谢谢你的通知

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


【解决方案1】:

请改成这样,从流中读取的代码行向上移动

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

创建.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"/>

【讨论】:

  • 不工作的兄弟是在图像字段中保存 HttpPostedFileWrapper
  • 你能把文章图片改成字节[] 并去掉 Convert.ToBase64String 吗?
  • 当我将图像更改为字节时隐藏输入文件,因为我上传文件这是我的剃须刀输入@Html.EditorFor(model =&gt; model.image, new { htmlAttributes = new { @class = "form-control", @type = "file" ,@name= "postedFile" ,@id= "postedFile" } })
【解决方案2】:

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

article.image = postedFile.FileName;

【讨论】:

  • 我已经这样做了,并尝试另存为文件,但不工作兄弟
  • 你能具体解释一下你想做什么吗?
  • 好的兄弟我想创建新的Product 包含标题、描述、图片和它们的类别,当我通过创建发布数据时保存数据但不显示图像,当我检查数据库图片字段时,我找到了价值图片的HttpPostedFileWrapper 不是 p.png 或 product.jpg
  • 您希望将数据库中的文件保存为“文件名.文件扩展名”。如果是这样,请您试试上面的代码吗?
  • 是的,我试了一下,但不起作用兄弟你能用我的代码编辑响应吗谢谢兄弟
【解决方案3】:

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

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

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

【讨论】:

  • 是的,我只想获取示例 product.png 的文件值并将其作为字符串保存在数据库的图片字段中
  • 查看我的下一条评论
【解决方案4】:

只是一个更新。我最后使用了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" />

感谢大家的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 2019-04-18
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多