How to upload image in ASP.NET MVC

By FoxLearn 2/18/2024 1:20:48 AM   233
I have a properties in my Item model class like FoodType, Price, Description, Amount, Image.

I have written HttpPostedFileBase File in my Item model class for image upload and change the Create .cshtml file to

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

for image upload to database.

Can anyone help me how to write whole code for [HttpPost] Create action method.

FoodType is foreignkey one to many relationship.

My model Entity connectionstring object is FoodAppEntities db = new FoodAppEntities()

Answer

You can use the code below to upload an image to web server in asp.net mvc

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    {
        try
        {
            string path = Server.MapPath($"~/images/");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            file.SaveAs(Path.Combine(path, file.FileName));
            using (var img = Image.FromStream(file.InputStream))
            {
                if (img.RawFormat.Equals(ImageFormat.Png) | img.RawFormat.Equals(ImageFormat.Jpeg))
                {
                    if (img.Width > 145 || img.Height > 110)
                    {
                        int imgHeight = 115;
                        int imgWidth = 145;
                        Image thumb = img.GetThumbnailImage(imgWidth, imgHeight, () => false, IntPtr.Zero);
                        thumb.Save(Path.Combine(path, file.FileName));
                    }
                }
            }
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            ViewBag.Message = "ERROR: " + ex.Message;
        }
    }
    else
    {
        ViewBag.Message = "Please select your upload file.";
    }
    return RedirectToAction("Index");
}

Thank you for helping me out. But i have other properties also like FoodType, Price, Description, Amount, Image

Is it work for other properties also if i submit the properties with image.

Answer

You can modify your code to upload an image to IIS Server as shown below

[HttpPost]
[ValidateAntiForgeryToken]
[ActionAuthorize]
public ActionResult Edit(HttpPostedFileBase file, Item item)
{
    if (file != null && file.ContentLength > 0)
    {
        try
        {
            string path = Server.MapPath($"~/images/");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            file.SaveAs(Path.Combine(path, file.FileName));
            using (var img = Image.FromStream(file.InputStream))
            {
                if (img.RawFormat.Equals(ImageFormat.Png) | img.RawFormat.Equals(ImageFormat.Jpeg))
                {
                    if (img.Width > 145 || img.Height > 110)
                    {
                        int imgHeight = 115;
                        int imgWidth = 145;
                        Image thumb = img.GetThumbnailImage(imgWidth, imgHeight, () => false, IntPtr.Zero);
                        thumb.Save(Path.Combine(path, file.FileName));
                    }
                }
            }
            item.Image = file.FileName;            
            //etc...
            bool result = AppService.Item.Save(item);
            if (result)
                return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            ViewBag.Message = "ERROR: " + ex.Message;
        }
    }
    else
    {
        ViewBag.Message = "Please select an upload file";
    }
    return View(item);
}