mor
mor

Reputation: 81

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. 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 –

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

Upvotes: 0

Views: 463

Answers (4)

A.G.
A.G.

Reputation: 16

Your postedfile parameter is a HttpPostedFileBase-type parameter. 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;

Upvotes: 0

Rokonz Zaz
Rokonz Zaz

Reputation: 176

Just an update. I used varbinary in the end. 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 !

Upvotes: 0

Hien Nguyen
Hien Nguyen

Reputation: 18975

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?

[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

@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

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

Upvotes: 0

Rokonz Zaz
Rokonz Zaz

Reputation: 176

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

Upvotes: 0

Related Questions