views:

1784

answers:

6

In my code attached below, I'm trying to upload a file via ASP.NET. I am dynamically creating the FileUpload control so that means it's not in my ViewState which (I think) means I can't use the control for uploading files unless I use the old fashioned multipat/form-data way which I don't want to do. I need to be able to allow the user to create multiple FileUpload fields and then when they click the Upload File(s) button, it loops through all the FileUpload fields and uploads them to the server.

I'm sure there's a way to do this that I'm just not thinking of - TIA!

For some reason I can't figure out how to paste code in this thing so you can view the code here: http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_23992755.html

+2  A: 

You can use Request.Files

It contains the uploaded files as HttpPostedFile objects.

foreach(HttpPostedFile file in Request.Files)
  file.SaveAs(...);
Think Before Coding
A: 

I get this error when I try that (which I assume is because there's no enctype="multipart/form-data" like I mention not wanting to have to do in my original post):

Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.

Source Error:

Line 13: Line 14: Protected Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Line 15: For Each file As HttpPostedFile In Request.Files Line 16: Response.Write(file.FileName) Line 17: Next

EdenMachine
A: 

The problem is that the FileUpload control has locked off the FileName parameter from being set programmatically. The reason for this is to protect the user from some malicious script deciding that it wants to upload system files to the server instead of what the user wants.

You will not be able to use the FileUpload control in the situation you describe above, you'll want to seek out an alternative.

Dillie-O
A: 

"You will not be able to use the FileUpload control in the situation you describe above, you'll want to seek out an alternative."

Really? There's no way to save a dynamically created control into the ViewState or something so that your page remembers it's there so you can access it after a PostBack?

EdenMachine
+1  A: 

here is a longer version of the above: 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);
    }
  }");
KevinB
A: 

KevinB, you are GENIUS!! Thank you sir!!

EdenMachine