NiceToMytyuk
NiceToMytyuk

Reputation: 4277

Upload multiple images with <input=file> in ASPX

Actually I'm able to upload one file with the following input

<input type="file" name="FileUpload" style="display: none;" multiple="multiple" accept="image/*" />

But if I select more than one file it's loaded just the first one to the server, so how could I upload all selected files and like limit them to max 3 files?

Here is my codeBehind

 Sub LoadImage()
        Dim postedFile As HttpPostedFile = Request.Files("FileUpload")

        If postedFile IsNot Nothing And postedFile.ContentLength > 0 Then
            'Save the File.
            Dim filePath As String = Server.MapPath("~/images/") + Path.GetFileName(postedFile.FileName)
            postedFile.SaveAs(filePath)
        End If
    End Sub

Upvotes: 0

Views: 199

Answers (1)

Sunil
Sunil

Reputation: 21406

You need to use code like below to get all posted files else with your code you would end up with one file. Also, the file upload control should be visible else how will you see the Choose Files button.

Sub LoadImage()
   Dim postedFiles As HttpFileCollection = Request.Files  

   ''iterate the key collection to get all files for FileUpload control     
   For Each key As String In postedFiles.Keys
      If key = "FileUpload" then
           Dim postedFile As HttpPostedFile = postedFiles(key)
           If postedFile.ContentLength > 0 Then
             'Save the File.
             Dim filePath As String = Server.MapPath("~/images/") + Path.GetFileName(postedFile.FileName)
             postedFile.SaveAs(filePath)
           End If
      End If
   Next

End Sub

To validate that number of files posted in not greater than 3, you could use the function below on server side. You call this validation function before you process the loaded files and then show an appropriate validation message using an asp:label in your page if this function returns a false i.e. more than maximum number of files have been uploaded.

public Function IsNumberOfPostedFilesValid(fileUploadControlName as string, maxNumberOfFiles as Integer)

   Dim numberOfFiles as Integer = 0
   For Each key As String In Request.Files.Keys
     If key = fileUploadControlName Then
       numberOfFiles = numberOfFiles + 1
     End If
   Next

   Return (numberOfFiles <= maxNumberOfFiles)

End Function

Upvotes: 1

Related Questions