<b>Title:</b> <asp:TextBox ID="PictureTitle" runat="server" /> <br /> <b>Picture:</b> <asp:FileUpload ID="UploadedFile" runat="server" /> <br /> <asp:LinkButton ID="btnInsert" runat="server" Text="Insert" /> <asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" /> |
Protected Sub btnInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnInsert.Click ''确保一个文件被成功上传 If UploadedFile.PostedFile Is Nothing OrElse String.IsNullOrEmpty(UploadedFile.PostedFile.FileName) OrElse UploadedFile.PostedFile.InputStream Is Nothing Then 显示错误信息 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 ''无效的文件类型上传 显示错误信息 Exit Sub End Select ''与数据库连接并且把一条新记录插入到Products表格中 Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("ImageGalleryConnectionString").ConnectionString) Const SQL As String = "INSERT INTO [Pictures] ([Title], [MIMEType], [ImageData]) VALUES (@Title, @MIMEType, @ImageData)" Dim myCommand As New SqlCommand(SQL, myConnection) myCommand.Parameters.AddWithValue("@Title", PictureTitle.Text.Trim()) myCommand.Parameters.AddWithValue("@MIMEType", MIMEType) ''把FileUpload控件的InputStream加载到字节数组中 Dim imageBytes(UploadedFile.PostedFile.InputStream.Length) As Byte UploadedFile.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length) myCommand.Parameters.AddWithValue( "@ImageData", imageBytes) myConnection.Open() myCommand.ExecuteNonQuery() myConnection.Close() End Using End Sub |