1

How to Save multiple files in asp.net 4.0 by Fileupload Control with multiple fileupload control? I have two fileupload control one for image and second for thumbimage. So I want to save multiple image and thumbimage ?

2 Answers2

0

You are actually overwriting the fist file with the second one when you are in the loop. I would suggest you to create a list for the files and add to the list in the loop like below. You will then have a list of file when you can use firstOrDefault() for the first item as well as use Skip() and Take() to select any item you want.

HttpFileCollection uploadedFiles = Request.Files;
List<HttpPostedFile> fileList1 = new List<HttpPostedFile>();
List<HttpPostedFile> fileList2 = new List<HttpPostedFile>();



for (int i = 0; i < uploadedFiles.Count; i++)
{
    HttpPostedFile hpf = uploadedFiles[i];
    var hpfKey = uploadedFiles.Keys[i];
    if (hpfKey.IndexOf("FileUpload1") > 0)
    {
        fileList1.Add(hpf);
    }
    if (hpfKey.IndexOf("FileUpload2") > 0)
    {
        fileList2.Add(hpf);
    }
}

Update:

Now to get the first file you call FirstOrDefault() on the list like below:

 fileList1.FirstOrDefault();

And to get the second file :

fileList1.Skip(1).FirstOrDefault();
RokM
  • 31
  • 4
0

HttpFileCollection uploadedFiles = Request.Files;

    int i = uploadedFiles.Count;


    List<HttpPostedFile> fileList1 = new List<HttpPostedFile>();
    List<HttpPostedFile> fileList2 = new List<HttpPostedFile>();

    if (i > 0)
    {
        for (int j = 0; j < i/2; j++)
        {
            fileList1.Add(uploadedFiles[j]);
        }
    }

    if (i > 0)
    {
        for (int j = i / 2; j < i; j++)
        {
            fileList2.Add(uploadedFiles[j]);
        }
    }

    int filecount = fileList1.Count;
   if (filecount > 0)
    {
        for (int j = 0; j < filecount; j++)
        {
     string image =  fileList1[j].FileName;
    fileList1[j].SaveAs(imagepath);
    string image =  fileList2[j].FileName;
    fileList2[j].SaveAs(imagepath);
    }
   }