Maintain order of selected files in FileUpload with AllowMultiple=true

Viewed 1461

I have an <asp:FileUpload> control with the property AllowMultiple set to true:

<asp:fileupload id="FileUpload" runat="server" allowmultiple="true" cssclass="fileUpload btn btn-sm btn-default" onchange="preloadImages()" />

<div class="field col-md-2 col-md-offset-1 immScarpePreview MainPreviewBox">
 <asp:image id="Image1" runat="server" visible="false" cssclass="img-responsive" />
 <asp:button id="ImmButton" runat="server" text="Upload" onclick="ImmButton_Click" cssclass="hidden" />
</div>

In my JavaScript function, I simulate a click on the invisible button:

<script>
    function preloadImages() {
        $('#<%=ImmButton.ClientID%>').trigger('click');
    }
</script>

In the code-behind, I save the files to a temporary folder, and I display the uploaded images in the <asp:Image> controls:

 protected void ImmButton_Click(object sender, EventArgs e)
 {
        if (FileUpload.HasFile)
        {
            try
            {
                int cont = 0;
                byte[] fileData = null;
                foreach (HttpPostedFile file in FileUpload.PostedFiles)
                {
                    if (cont == 0)
                    {
                        using (var binaryReader = new BinaryReader(file.InputStream))
                            fileData = binaryReader.ReadBytes(file.ContentLength);
                        File.WriteAllBytes(Server.MapPath("immScarpe/tmp/" + file.FileName), fileData);
                        setImage1("immScarpe/tmp/" + file.FileName);
                    }
                    else if (cont == 1)
                    {
                        using (var binaryReader = new BinaryReader(file.InputStream))
                            fileData = binaryReader.ReadBytes(file.ContentLength);
                        File.WriteAllBytes(Server.MapPath("immScarpe/tmp/" + file.FileName), fileData);
                        setImage2("immScarpe/tmp/" + file.FileName);
                    }
                    else if (cont == 2)
                     //and so on...

                    //so on...
                    cont++;
                }
            }
            catch(Exception ex)
            {
                //error writing file
                Console.Write(ex.Message);
            }
        }
 }

 private void setImage1(string image) //all equals for all the 5 images
 {
     Image1.ImageUrl = image;
     Image1.Visible = true;
 }

This is working perfectly but I need some help. When I loop through FileUpload.PostedFiles, the order of the selected images is alphabetical I think. I would like to keep the order of the user's selection. Is this possible?

1 Answers
Related