Abdul Hannan
Abdul Hannan

Reputation: 424

Post Images from Two upload controls in one view MVC

I have two file upload control. the first control accepts single file of type image which is basically the Product Icon. the second upload control allows multiple image uploads and it contains several images of the product.

Now I am able to Upload files successfully using following code

for (int i = 0; i < Request.Files.Count; i++)
        {
            var file = Request.Files[i];

            if (file != null && file.ContentLength > 0)
            {
                if (validImageTypes.Contains(file.ContentType))
                {
                    var fileName = Path.GetFileName(file.FileName);
                    LocationImage fileDetail = new LocationImage()
                    {
                        FileName = fileName,
                        Extension = Path.GetExtension(fileName),
                        ID = Guid.NewGuid()
                    };
                    fileDetails.Add(fileDetail);
                    var path = Path.Combine(Server.MapPath("~/Upload/Images"), fileDetail.ID + fileDetail.Extension);
                    file.SaveAs(path);
                }

This piece of code is saving file perfectly but i want to save the icon files in a separate Directory I somehow want to know that the file is coming from single upload control so that i can save it in Icon folder.

Upvotes: 1

Views: 1163

Answers (1)

Shyju
Shyju

Reputation: 218732

You can use named parameters for your action method instead of reading the file from Request.Files

So in your form (in your view), give 2 different names to your file input controls

<input type="file" name="productIcon" />
<input type="file" name="productImages" multiple />

Now in your action method, have 2 parameters with same name as the input file element's names.

[HttpPost]
public ActionResult Save(HttpPostedFileBase productIcon,
                                            IEnumerable<HttpPostedFileBase> productImages)
{
  // to do : Save these
  if(productIcon!=null)
  {
    // to do : Save icon image 
  }
  if(productImages!=null)
  {
     foreach(var img in productImages)
     {
       // to do : Save img
     } 
  }
  // to do : Return something
}

Upvotes: 3

Related Questions