Webforms Upload multiple files

Asked

Viewed 234 times

0

I have an app WebForms that needs to receive multiple files that will be associated with a specific type of my system.

Ex:

Type: [Driver’s license] | Filing cabinet: img001.png
Type: [Proof of residence] | Filing cabinet: comp001.pdf

I need to receive this information on a page WebForm .aspx.

If it was just to get the files, you could get it using the Request.Files, but I need to know the type of document to save in the bank.

I imagined doing something on how to use the name of the file fields as a array using arquivos[0], arquivos[1] and associate with the type (tipos[0], tipos[1]). Doing so could use the index I could ensure that the type would be related to the file. But I don’t know how to access this information on the pages .aspx.

With MVC I can do it well, but as I do not have the mastery with the WebForms I end up hitting myself a little with this.

How could I do it in a way without "Gambiarras"?

  • Managed to solve?

2 answers

0

I believe in this case a Repeater is ideal. With Repeater you can create multiple controls (Fileupload), have an index of each item and then perform the validation.

  1. Create Update Panel to have better content control and avoid refresh on the entire page;
  2. Create an upload button to validate and upload files;
  3. Create a Repeater to dynamically show the controls;
  4. Place Fileupad controls inside the Peater;
  5. Create a Hiddenfield to wait for the Item Index;
  6. Create Trigger for the upload button (prevent the file inserted in Fileupload from losing the information in postback);

Here’s a functional example. I hope it helps.

Page ASPX

    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:LinkButton Text="Enviar" ID="lblEnviar" OnClick="lblEnviar_Click" runat="server" />
            <br />

            <asp:Repeater runat="server" ID="rpt">
                <ItemTemplate>
                    File Upload <%# Eval("TipoDocumento") %>
                    <asp:HiddenField runat="server" ID="hdnIndex" Visible="false" Value='<%# Eval("Index") %>' />
                    <asp:FileUpload runat="server" ID="fuArquivos" AllowMultiple="false" />
                </ItemTemplate>
            </asp:Repeater>


        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="lblEnviar" />
        </Triggers>
    </asp:UpdatePanel>
    <br />
    <asp:Literal ID="ltlResultado" runat="server" />

ASPX.CS file

       //Objeto para fazer o transporte das informações
    public class DTO
    {
        public int Index { get; set; } //armazenar a posicao
        public string TipoDocumento { get; set; } //Descritivo do tipo do documento
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        //Simula uma chamada ao banco e carrega uma lista com os tipos necessários a serem enviados
        List<DTO> lst = new List<DTO>();

        lst.Add(new DTO() { Index = 0, TipoDocumento = "CNH" });
        lst.Add(new DTO() { Index = 1, TipoDocumento = "CPF" });

        //Popula o Repeater
        rpt.DataSource = lst;
        rpt.DataBind();
    }

    protected void lblEnviar_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        //verifica cada linha gerada no repeater
        foreach (RepeaterItem item in rpt.Items)
        {
            //Procurar o controle FileUpload
            FileUpload fuTemp = (FileUpload)item.FindControl("fuArquivos");

            //Procurar identificador 
            HiddenField hdnIndex = (HiddenField)item.FindControl("hdnIndex");

            //Verifica se tem arquivo
            if (fuTemp.HasFile)
            {
                string s = String.Format("O arquivo na posição {0}, tem o seguinte arquivo {1}", hdnIndex.Value, fuTemp.FileName);
                sb.Append(s);
                sb.Append("<br>");
            }
        }

        //Imprime o resultado em um label apenas para teste.
        ltlResultado.Text = sb.ToString();
    }

0

Simply user multiple components of type asp:FileUpload and access them using their respective name in the desired event by following the example below;

<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="false"/>
<asp:FileUpload ID="FileUpload2" runat="server" AllowMultiple="false"/>
protected void btnUpload_Click(object sender, EventArgs e)
{
    if(FileUpload1.HasFile)
    {
        var file1info = FileUpload1.FileName + " - " + FileUpload1.PostedFile.ContentLength + " Bytes.";
        //logica para salvar
    }

    if(FileUpload2.HasFile)
    {
        var file2info = FileUpload2.FileName + " - " + FileUpload2.PostedFile.ContentLength + " Bytes.";
        //logica para salvar
    }
}
  • But in my case it would have to be dynamic. And I don’t want the client to have to wait to re-load the page to add a new field. I would replicate the fields using JS

  • In this format both files will go up in a single post, did not understand your objection

  • It is that I may have 1 or N files. I will not have a fixed number of files

Browser other questions tagged

You are not signed in. Login or sign up in order to post.