Create an ASP.NET MVC Data-based Web App Pt 7 - Upload and Save an Image in the database

Continuing on from part 6, Create, Edit, Update, Delete Fabrics, Now let's upload an image swatch for the fabric and save the filename to the database. Once I figured it out, it's fairly simple to implement. I got most of my information from this site, https://www.c-sharpcorner.com/blogs/how-to-upload-image-and-save-image-in-project-folder-in-mvc1, but I modified it for my purposes on my app as follows:

Step 1: Open the Create view in the Fabrics Controller. The framework automatically created the scaffolding for the view but we are going to tweak it a bit to our needs.
Find the ImagePath form group in the view, cut and paste it to the top of the form underneath the first hr tag.

 

Step 2: Replace that code for the ImagePath, with the following: 

<div class="form-group">
        <label class="control-label col-md-2">Thumbnail</label>
        <div class="col-md-10">
            <div>
                <img id="user_img" width="100" />
            </div>
            <input type="file" title="Upload Image" id="file" name="file" onchange="show(this)" />
            @Html.ValidationMessageFor(model => model.ImagePath, "", new { @class = "text-danger" })
            <script type="text/javascript">
                function show(input) {
                    if (input.files && input.files[0]) {
                        var filereader = new FileReader();
                        filereader.onload = function (e) {
                            $('#user_img').attr('src', e.target.result);
                        }
                        filereader.readAsDataURL(input.files[0]);
                    }
                }
            </script>
        </div>
    </div>

Step 3: Add the following code parameters to the @Html.BeginForm helper:

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

This is really important! The input tag will not pass the file name to the controller without specifying that.

 

Step 4: Add the following code to the FabricController in the Create (HTTPPOST) action method:

public ActionResult Create([Bind(Include = "FabricId,MainCategory,SubCategory1,SubCategory2,Name,ImagePath,Location,Type,Weight,Content,Design,Brand,Quantity,Width,Source,Notes,ItemsSold")] Fabric fabric, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                var filename = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/images"), filename);
                fabric.ImagePath = filename;
                file.SaveAs(path);
                db.Fabrics.Add(fabric);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(fabric);
        }

Notice the "HttpPostedFileBase file" parameter added to the Create method. This passes in the file object to the method so we can retrieve the filename and other information about the uploaded file.

Step 5: Build and Run (Ctrl + f5) the application. It's easier if you are in the View for the Fabrics list when hitting Ctrl + F5. Then, click "Create New" and test the Create form by selecting an image thumbnail file and entering dummy info for the fabric. Click "Save" and it should take you back to the Fabrics List view. If not, you did something wrong, and the file did not save properly to the database.

Add comment

Loading