locked
Multiple uploads with different upload buttons and only one submite RRS feed

  • Question

  • User1426634748 posted

    Same part of my webpage has a view that will contain images, and those images will come from the database , but only their path.
    I will upload the image, save the path, and retrieve it on the view.
    I  have a table with multiple columns for each image I want
    So I have this:
    I have a form with multiple upload buttons and only one submit.
    The user need to optionally upload one or multiple files, and when he submit I will save to a folder only the ones he choosed.

    I have multiple upload buttons because, I know I can use

    HttpPostedFile[] files

    in the Controller, but I'm afraid that I won't be able to edit to choose in the case of the user just wants to insert or update for the 3rd or n column.
    So, I'm assuming if I have multiple upload buttons, in theory... I can get track of each and say something like "if upload1 !=null >insert/update imagePath1 in the database.

    Any help with my code or any suggestion to make me archive the same goal is welcomed, as long as is a simple way.
    My code:

      public ActionResult Upload()
            {
    
                ViewBag.idCompany = new SelectList(db.Company, "id", "name");
                return View();
            }
            
            [HttpPost]
            public ActionResult Upload(HttpPostedFile image1)
            {
    
    
                string path = string.Empty;
                try
                {
    
      
    
    
    
                    if (image1 != null)
                    { 
    
                        path = Path.Combine(Server.MapPath("~/App_Data/Images/Company/6"), Path.GetFileName(image1.FileName));
    
                        //HttpPostedFile up =default;
                        //up.SaveAs(path);
    
                    }
                    ViewBag.FileStatus = $"File uploaded successfully. {path}";
                    
                }
                catch (Exception ex)
                {
                    ViewBag.FileStatus = $"Error while file uploading. {ex.Message}"; ;
                }
    
                ViewBag.idCompany = new SelectList(db.Company, "id", "name");
                return View();
            }

    View:

    @model TwoDBs.Models.ImagensCreche
    
    @{
        ViewBag.Title = "Upload";
    }
    
    <h2>Upload</h2>
    
    
        @using (Html.BeginForm("Upload", "ImagensCreches", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
    
            @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>ImagensCreche</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    
        <div class="form-group">
            @Html.LabelFor(model => model.image1, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.image1, new { htmlAttributes = new { @class = "form-control", @type = "file" } })
                @Html.ValidationMessageFor(model => model.image1, "", new { @class = "text-danger" })
            </div>
        </div>
    
    
    
        <div class="form-group">
            @Html.LabelFor(model => model.image2, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.image2, new { htmlAttributes = new { @class = "form-control", @type = "file" } })
                @Html.ValidationMessageFor(model => model.image2, "", new { @class = "text-danger" })
            </div>
        </div>
    
    
        <div class="form-group">
            @Html.LabelFor(model => model.idCompany, "idCompany", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("idCompany", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.idCompany, "", new { @class = "text-danger" })
            </div>
        </div>
    
        @ViewBag.FileStatus
    
        <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>
            @Html.ActionLink("Back to List", "Index")
        </div>
    


    Image in Browser


     

    Friday, July 24, 2020 7:39 AM

Answers

  • User1686398519 posted

    Hi Belarmino Vicenzo,

    The different upload buttons have their own names, so you can track them by name. "Editorfor" will generate a button with the name attribute. Therefore, you can receive parameters based on the button name.

    Controller

            [HttpPost]
            public ActionResult Upload(ImagensCreche ic,HttpPostedFileBase image1, HttpPostedFileBase image2)
            {
                string path = string.Empty;
                try
                {  
                            if (image1 != null)
                            {
                                path = Path.Combine(Server.MapPath("~/App_Data/Images/Company/6"), Path.GetFileName(image1.FileName));
                                ic.image1 = path;
                            ViewBag.FileStatus = $"File uploaded successfully. {path}";
                        }
                        else
    
                        {
                            ic.image1 = null;
                        }
                            if (image2 != null)
                            {
                                path = Path.Combine(Server.MapPath("~/App_Data/Images/Company/6"), Path.GetFileName(image2.FileName));
                                ic.image2 = path;
                                ViewBag.FileStatus = $"File uploaded successfully. {path}";
                        }
                        else
                        {
                            ic.image2 = null;
                        }
                        //Save ic  to databse
                }
                catch (Exception ex)
                {
                    ViewBag.FileStatus = $"Error while file uploading. {ex.Message}"; ;
                }
                ViewBag.idCompany = new SelectList(db.Company, "id", "name");
                return View();
            }

    Here is the result.

    Best regards,

    Yihui Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2020 9:44 AM

All replies

  • User1686398519 posted

    Hi Belarmino Vicenzo,

    The different upload buttons have their own names, so you can track them by name. "Editorfor" will generate a button with the name attribute. Therefore, you can receive parameters based on the button name.

    Controller

            [HttpPost]
            public ActionResult Upload(ImagensCreche ic,HttpPostedFileBase image1, HttpPostedFileBase image2)
            {
                string path = string.Empty;
                try
                {  
                            if (image1 != null)
                            {
                                path = Path.Combine(Server.MapPath("~/App_Data/Images/Company/6"), Path.GetFileName(image1.FileName));
                                ic.image1 = path;
                            ViewBag.FileStatus = $"File uploaded successfully. {path}";
                        }
                        else
    
                        {
                            ic.image1 = null;
                        }
                            if (image2 != null)
                            {
                                path = Path.Combine(Server.MapPath("~/App_Data/Images/Company/6"), Path.GetFileName(image2.FileName));
                                ic.image2 = path;
                                ViewBag.FileStatus = $"File uploaded successfully. {path}";
                        }
                        else
                        {
                            ic.image2 = null;
                        }
                        //Save ic  to databse
                }
                catch (Exception ex)
                {
                    ViewBag.FileStatus = $"Error while file uploading. {ex.Message}"; ;
                }
                ViewBag.idCompany = new SelectList(db.Company, "id", "name");
                return View();
            }

    Here is the result.

    Best regards,

    Yihui Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2020 9:44 AM
  • User1426634748 posted

    That was just a sample code.
    My original code have 9 upload buttons.
    If I do that, I wouldn't be writing bad code?

    Like imagine if my project requirements change and I have even more?
    I would have to use a lot of ifs or switch statements, this wouldn't be signs of code smell?

    Tuesday, July 28, 2020 8:25 AM
  • User1686398519 posted

    Hi Belarmino Vicenzo,

    If you want to reduce the amount of if’s code, and the uploaded file corresponds to the properties of the model, you can set the model properties to a list, and execute the if multiple times through the for loop.

    Model

        public class ImagensCreche
        {
            [Key]
            public int id { get; set; }
            public List<files> files { get; set; }
            public string idCompany { get; set; }
            public string name { get; set; }
        }
        public class files
        {
            [Key]
            public int id { get; set; }
            public string filepath { get; set; }
        }

    View

        @for (var i = 0; i < 9; i++)
        {
            <div class="form-group">
                @Html.LabelFor(model => model.files[i], htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.files[i], new { @class = "form-control", type = "file" })
                    @Html.ValidationMessageFor(model => model.files[i], "", new { @class = "text-danger" })
                </div>
            </div>
        } 

    Controller

            [HttpPost]
            public ActionResult Upload(ImagensCreche ic,HttpPostedFileBase[] files)
            {
                string path = string.Empty;
                try
                {
                    for (int i = 0; i < 9; i++)
                    {
                        if (files[i] != null)
                        {
                            path = Path.Combine(Server.MapPath("~/App_Data/Images/Company/6"), Path.GetFileName(files[i].FileName));
                            ViewBag.FileStatus = $"File uploaded successfully. {path}";
                        }
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.FileStatus = $"Error while file uploading. {ex.Message}"; ;
                }
                ViewBag.idCompany = new SelectList(db.Company, "id", "name");
                return View();
            }

    Here is the result.

    Best regards,

    Yihui Sun

    Thursday, July 30, 2020 1:40 AM
  • User1426634748 posted

    Thanks, bro :) 

    Thursday, July 30, 2020 5:27 AM
  • User-1244692504 posted

    Thank you YihuiSun. I was about to ask the same question when I saw your answer. Please how do I retrieve the images back to be displayed in the razor view for only array indexes that have an image attached?

    Thank you for your anticipated assistance.

    Saturday, August 1, 2020 9:03 PM