[RESOLVED]how can I upload an image and save the url in the database

I want to be able to upload an image to the server but instead of saving the image as byte in the database I want to save the path so that in the view page I call the image by it’s path.also the image when uploaded it should be uploaded in a certain
folder if folder not found create one.all this should be using MVC5 any help is really appreciated

lolo512

I want to be able to upload an image to the server but instead of saving the image as byte in the database I want to save the path so that in the view page

And the problem is …? To save use File.WriteAllBytes. 

I want a full code I don’t know how to do so im a new learner of MVC I appreciate your help

Hi,

For your references:

  1. https://www.youtube.com/watch?v=9LPIu_BvatE
  2. https://www.youtube.com/watch?v=rpmtFvduwyI

Here I do for both save to database or (not and) to a folder, depend on it’s size:

A helper class, is used when save to database:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.IO;

namespace PersonEntity.Model
{
    public static class ConvertFile
    {
        public static byte[] ImageToByte(HttpPostedFileBase imageFile)
        {
            if (imageFile == null) { return null; }
            return (imageFile.ContentType == "image/jpeg" || imageFile.ContentType == "image/gif" || imageFile.ContentType == "image/png") ? FileToByte(imageFile) : null;
        }

        public static byte[] FileToByte(HttpPostedFileBase file)
        {
            byte[] data = new byte[file.ContentLength];
            file.InputStream.Read(data, 0, file.ContentLength);
            return data;
        }
    }
}

Need a partial class to the class where image class is defined, for "File":

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace PersonEntity.Model
{
    [MetadataType(typeof(ProductPhotoMetadata))]
    public partial class ProductPhoto
    {
        [DisplayFormat(NullDisplayText = "n/a")]
        //[Required(ErrorMessage = "Please select image file")]
        public HttpPostedFileBase File { get; set; }
    }
}

Controller, add ",File" almost at the end of the "public Action Result:…….,File")] ProductPhoto…….. It si boleded and underlined

        // GET: ProductPhotoes/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ProductPhoto productPhoto = db.ProductPhotoes.Find(id);
            if (productPhoto == null)
            {
                return HttpNotFound();
            }
            return View(productPhoto);
        }

        // GET: ProductPhotoes/Create
        public ActionResult Create()
        {
            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria");
            return View();
        }

        // POST: ProductPhotoes/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Photo,PhotoFileName,ThumbnailUrl,LargePhoto,LargePhotoFileName,LargeUrl,ModifiedDate,ImageSize,Title,Caption,ProductPhotoCriteriaId,File")] ProductPhoto productPhoto)
        {
            productPhoto.ModifiedDate = DateTime.Now;
            if (productPhoto.File != null)
            {
                if (productPhoto.File.ContentLength > (2 * 1024 * 1024) && productPhoto.File.ContentLength < 1)
                {
                    ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
                    return View(productPhoto);
                }
                productPhoto.ImageSize = productPhoto.File.ContentLength;

                /** Photo dibawh 61KB disimpan di database, sisanya disimpan di folder, dengan nama NewGuid() **/
                if (productPhoto.File.ContentLength < 61676)
                {
                    productPhoto.Photo = ConvertFile.ImageToByte(productPhoto.File);
                }
                else
                {
                    productPhoto.PhotoFileName = Guid.NewGuid() + Path.GetExtension(productPhoto.File.FileName); // productPhoto.File.FileName;
                    productPhoto.Photo = null;
                    var path = Path.Combine(Server.MapPath("~/images/normal"), productPhoto.PhotoFileName);
                    productPhoto.File.SaveAs(path);
                }
            }

            if (ModelState.IsValid)
            {
                db.ProductPhotoes.Add(productPhoto);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
            return View(productPhoto);
        }

        // GET: ProductPhotoes/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ProductPhoto productPhoto = db.ProductPhotoes.Find(id);
            if (productPhoto == null)
            {
                return HttpNotFound();
            }
            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
            return View(productPhoto);
        }

        // POST: ProductPhotoes/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Photo,PhotoFileName,ThumbnailUrl,LargePhoto,LargePhotoFileName,LargeUrl,ModifiedDate,ImageSize,Title,Caption,ProductPhotoCriteriaId,File")] ProductPhoto productPhoto)
        {
            productPhoto.ModifiedDate = DateTime.Now;

            if (productPhoto.File != null)
            {
                if (productPhoto.File.ContentLength > (2 * 1024 * 1024) && productPhoto.File.ContentLength < 1)
                {
                    ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
                    return View(productPhoto);
                }
                productPhoto.ImageSize = productPhoto.File.ContentLength;
                if (productPhoto.File.ContentLength < 61676)
                {
                    productPhoto.PhotoFileName = null;
                    productPhoto.Photo = ConvertFile.ImageToByte(productPhoto.File);
                }
                else
                {
                    productPhoto.PhotoFileName = Guid.NewGuid() + Path.GetExtension(productPhoto.File.FileName); // productPhoto.File.FileName;
                    productPhoto.Photo = null;
                    var path = Path.Combine(Server.MapPath("~/images/normal"), productPhoto.PhotoFileName);
                    productPhoto.File.SaveAs(path);
                }
            }

            if (ModelState.IsValid)
            {
                db.Entry(productPhoto).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
            return View(productPhoto);
        }

Create.cshtml, attention on "@using (Html.BeginForm(…………………..))"

@model PersonEntity.Model.ProductPhoto

@{
    ViewBag.Title = "Create: " + @EstateAgency.Admin.Resource.Product + " Photo";
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm("Create", "ProductPhotoes", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>ProductPhoto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.File, new { type = "file" })
                @Html.ValidationMessage("CustomError")
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ThumbnailUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ThumbnailUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ThumbnailUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargeUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargeUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargeUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Caption, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Caption, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Caption, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProductPhotoCriteria.Criteria, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ProductPhotoCriteriaId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ProductPhotoCriteriaId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    <br />
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Edit.cshtml, attention on @using same with Create.cshtml:

@model PersonEntity.Model.ProductPhoto

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm("Edit", "ProductPhotoes", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>ProductPhoto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.File, new { type = "file" })
                @Html.ValidationMessage("CustomError")
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PhotoFileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PhotoFileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PhotoFileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ThumbnailUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ThumbnailUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ThumbnailUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargePhoto, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargePhoto, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargePhoto, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargePhotoFileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargePhotoFileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargePhotoFileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargeUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargeUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargeUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ImageSize, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ImageSize, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ImageSize, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Caption, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Caption, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Caption, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProductPhotoCriteria.Criteria, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ProductPhotoCriteriaId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ProductPhotoCriteriaId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    <br />
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

You may need to modify Web.config for larger file, add "maxRequestLength="2097152":

  <system.web>
    <globalization culture="auto" uiCulture="auto" />
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" maxRequestLength="2097152" />
  </system.web>

Have fun

Hi lolo512,

Thanks for your post.

According to your description,

lolo512

how can I upload an image and save the url in the database

Here is a sample,you can refer to the following code snippet:

table:

CREATE TABLE [dbo].[tblA]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [fname] NVARCHAR(50) NULL, 
    [lname] NVARCHAR(50) NULL, 
    [imageUrl] NVARCHAR(50) NULL
)
  • Creat an "Images" folder in Solution explorer.
  • Create an ADO.NET Entity Data Model (in this example is "Database1Entities") 
  • Home Controller: 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace test2.Controllers
    {
    public class HomeController : Controller
    {
    public ActionResult Index()
    {
        return View();
    }
    
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
    
        if (file != null)
        {
            Database1Entities db = new Database1Entities();
            string ImageName = System.IO.Path.GetFileName(file.FileName);
            string physicalPath =Server.MapPath("~/images/"+ ImageName);
    
            // save image in folder
            file.SaveAs(physicalPath);
    
            //save new record in database
            tblA newRecord = new tblA();
            newRecord.fname = Request.Form["fname"];
            newRecord.lname = Request.Form["lname"];
            newRecord.imageUrl = ImageName;
            db.tblAs.Add(newRecord);
            db.SaveChanges();
    
        }
        //Display records
        return RedirectToAction("../home/Display/");
    }
    
    public ActionResult Display()
    {
        return View();
    }
    }
    }
  • Index View 

    @{
       ViewBag.Title = "Index";
    }
    
    @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
                        new { enctype = "multipart/form-data" }))
    {
    <div>
    First name<br />
    @Html.TextBox("fname") <br />
    Last name<br />
    @Html.TextBox("lname") <br />
    Image<br />
    <input type="file" name="file" id="file" style="width: 100%;" /> <br />
    <input type="submit" value="Upload" class="submit" />
    </div>    
    }
  • Display View 

    @{
        ViewBag.Title = "Display";
    }
    
    @{
       test2.Database1Entities db = new test2.Database1Entities();
    }
    @using (Html.BeginForm())
    {
    <table border="1">
    <thead>
        <tr>
            <th>Image</th>
            <th>First name</th>
            <th>Last name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in db.tblAs)
        {
            <tr>
                <td><img src="~/images/@item.imageUrl" width="100" height="100" /></td>
                <td>@item.fname</td>
                <td>@item.lname</td>
            </tr>
        }
    </tbody>
    </table>
    }

Output:

/Home/ 

/home/Display/ 

More information:

http://forums.asp.net/t/1981336.aspx?Storing+Image+Url+in+Database

http://stackoverflow.com/questions/17499259/upload-a-picture-to-a-database-in-asp-mvc-4

Hope this can be helpful.

Best Regards,

Eileen

thank you for the reply it was very helpful. I need help in one more thing, instead of first and last name I have category which I am supposed to read from a database table category (ID-categoryName) and depending on the selected value the images is saved
in a folder of that selected value.

for example selected value :basketball.

the image path is: ~/basketball/fileName

can you help me with that??

Leave a Reply