实际上我可以使用以下输入上传一个文件
<input type="file" name="FileUpload" style="display: none;" multiple="multiple" accept="image/*" />
但是,如果我选择了多个文件,它只会将第一个文件加载到服务器,那么我该如何上传所有选择的文件,并且将它们限制为最多3个文件?
这是我的代码背后
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
答案 0 :(得分: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显示适当的验证消息。
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