ファイルアップロードコントロールがあります。それをクリックすると、複数のファイルを選択したいと思います。
どうすればそうできますか?
aspx code
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick ="UploadMultipleFiles" accept ="image/gif, image/jpeg" />
<hr />
<asp:Label ID="lblSuccess" runat="server" ForeColor ="Green" />
Code Behind:
protected void UploadMultipleFiles(object sender, EventArgs e)
{
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
string fileName = Path.GetFileName(postedFile.FileName);
postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
}
lblSuccess.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
}
これらのコントロールを使用できる他のオプションがあり、これらには複数のアップロード オプションがあり、これらのコントロールには Ajax もサポートされています
1)フラジシアン
2)バラム
3)サブグリム ファイルアップロード
default.aspx コード
<asp:FileUpload runat="server" id="fileUpload1" Multiple="Multiple">
</asp:FileUpload>
<asp:Button runat="server" Text="Upload Files" id="uploadBtn"/>
default.aspx.vb
Protected Sub uploadBtn_Click(sender As Object, e As System.EventArgs) Handles uploadBtn.Click
Dim ImageFiles As HttpFileCollection = Request.Files
For i As Integer = 0 To ImageFiles.Count - 1
Dim file As HttpPostedFile = ImageFiles(i)
file.SaveAs(Server.MapPath("Uploads/") & file.FileName)
Next
End Sub
.NET 4.5 以降の FileUpload.AllowMultiple プロパティを使用すると、コントロールで複数のファイルを選択できます。
4.0 (vs 2010) のような 4.5 以下では、2 つの js ファイル ( http://code.jquery.com/jquery-1.8.2.jsおよびhttp://code ) を使用して、1 つのコントロールで複数のファイルをアップロードするために jquery を使用できます 。 google.com/p/jquery-multifile-plugin/
aspx ファイルのアップロード タグに、class="multi" のように追加します。
<asp:FileUpload ID="FileUpload1" class="multi" runat="server" />
実際の例が必要な場合は、リンクダウンロード サンプルにアクセスしてください。
以下のコードを試すことができます:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim j As Integer = 0
Dim hfc As HttpFileCollection = Request.Files
Dim PathName As String
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("~/E:\") & System.IO.Path.GetFileName(hpf.FileName))
PathName = Server.MapPath(hpf.FileName)
If j < hfc.Count Then
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim sqlquery As String
sqlquery = "Insert_proc"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand(sqlquery, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@FilePath", SqlDbType.VarChar).Value = PathName
j = j + 1
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
If j = hfc.Count Then
Exit Sub
End If
End If
End If
Next
Catch generatedExceptionName As Exception
Throw
End Try
End Sub
.Net 4.5 (下位バージョンではこれを簡単にサポートしていない) を使用していて、jQuery を使用して物事を本当にシンプルで簡単にすることができる場合、この非常にシンプルなソリューションに出くわします。