五、上传图像并使用ASP.NET 2.0数据源控件代码存储二进制数据
尽管ADO.NET方法工作在一个ASP.NET 2.0应用程序环境下,但是,你还能够使用ASP.NET 2.0的数据源控件来把二进制数据存储到一个数据库,这不要求你编写ADO.NET代码。在这个演示程序中所使用的SqlDataSource控件包含了一个InsertCommand,以及相应于Title,MIMEType和ImageData值的参数:
<asp:SqlDataSource ID="UploadPictureDataSource" runat="server" ConnectionString="" InsertCommand="INSERT INTO [Pictures] ([Title], [MIMEType], [ImageData]) VALUES (@Title, @MIMEType, @ImageData)"> <InsertParameters> <asp:Parameter Name="Title" Type="String" /> <asp:Parameter Name="MIMEType" Type="String" /> <asp:Parameter Name="ImageData" /> </InsertParameters> </asp:SqlDataSource> |
Protected Sub UploadPictureUI_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles UploadPictureUI.ItemInserting ''引用FileUpload控件 Dim UploadedFile As FileUpload = CType(UploadPictureUI.FindControl( "UploadedFile"), FileUpload) ''确保已经成功上传一个文件 If UploadedFile.PostedFile Is Nothing OrElse String.IsNullOrEmpty(UploadedFile.PostedFile.FileName) OrElse UploadedFile.PostedFile.InputStream Is Nothing Then 显示错误信息 e.Cancel = True Exit Sub End If ''确保我们在处理一个JPG或GIF文件 Dim extension As String = Path.GetExtension(UploadedFile.PostedFile.FileName).ToLower() Dim MIMEType As String = Nothing Select Case extension Case ".gif" MIMEType = "image/gif" Case ".jpg", ".jpeg", ".jpe" MIMEType = "image/jpeg" Case ".png" MIMEType = "image/png" Case Else ''无效文件类型上载 显示错误信息 e.Cancel = True Exit Sub End Select "指定MIMEType和ImageData参数的值 e.Values("MIMEType") = MIMEType ''把FileUpload的InputStream加载进字节数组中 Dim imageBytes(UploadedFile.PostedFile.InputStream.Length) As Byte UploadedFile.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length) e.Values( "ImageData") = imageBytes End Sub |