How can I load a file from a dynamically generated FileUpload control using ASP.NET?

In my code below, I am trying to upload a file via ASP.NET. I am dynamically creating a FileUpload control, so this means it is not in my ViewState, which (I think) means that I cannot use the control to upload files unless I use the old fashioned multipat / form-data method that I do not want to do. I need to be able to allow the user to create multiple FileUpload fields, and then when they click the Upload Files button, they process all the FileUpload fields and upload them to the server.

I'm sure there is a way to do this that I just don't think about - TIA!

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim fup As New FileUpload()
        fup.ID = "FileUpload1"

        PlaceHolder1.Controls.Add(fup)
    End Sub

    Protected Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        ' HOW DO I GET THE FILE THAT WAS SELECTED IN THE DYNAMICALLY CREATE FILEUPLOAD CONTROL?
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="padding:13px">
        <asp:Button ID="btnAdd" runat="server" Text="Add FileUpload Control" OnClick="btnAdd_Click" />
        <br /><br />
        <asp:PlaceHolder ID="PlaceHolder1" runat="server" />
        <br /><br />
        <asp:Button ID="btnUploadFile" runat="server" Text="Upload File(s)" OnClick="btnUploadFile_Click" />
    </div>
    </form>
</body>
</html>

      

0


source to share


3 answers


here's a longer version: C #



print("HttpFileCollection UploadedFiles = Request.Files;
  HttpPostedFile UserPostedFile;
  int UploadFileCount = UploadedFiles.Count;
  if (UploadFileCount >= 1)
  {
    for (int i = 0; i < UploadFileCount; ++i)
    {
      UserPostedFile = UploadedFiles[i];
      UserPostedFile.SaveAs(UserPostedFile.FileName);
    }
  }");

      

+1


source


You can use Request.Files

It contains uploaded files as HttpPostedFile objects.



foreach(HttpPostedFile file in Request.Files)
  file.SaveAs(...);

      

+2


source


The problem is that the FileUpload control has blocked the FileName parameter from programmatic programming. The reason for this is to protect the user from some malicious script decisions that he wants to upload system files to the server and not what the user wants.

You won't be able to use the FileUpload control in the above situation, you need to look for an alternative.

0


source







All Articles