在ASPX中上传多个图像

问题描述 投票:0回答:1

实际上我可以使用以下输入上传一个文件

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

但是,如果我选择多个文件,它只是将第一个文件加载到服务器,那么我如何上传所有选定的文件,并将它们限制为最多3个文件?

这是我的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
asp.net vb.net
1个回答
1
投票

您需要使用下面的代码来获取所有已发布的文件,其中包含您的代码,最终会得到一个文件。此外,文件上传控件应该是可见的,否则您将如何看到“选择文件”按钮。

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

要验证发布的文件数不超过3,您可以使用服务器端的以下功能。在处理加载的文件之前调用此验证函数,然后在页面中使用asp:label显示相应的验证消息,如果此函数返回false,即已上载的文件数超过最大数量。

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
© www.soinside.com 2019 - 2024. All rights reserved.