asp.net上傳圖片

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

 Dim img As String
 '定義postedfile文件是儲存用戶上載的文件
 Dim postedfile As HttpPostedFile = File1.PostedFile
 '定義一個變量儲存用戶上載文件的大小
 Dim intImgSize As Int32
 '獲取用戶上傳文件的大小,
 intImgSize = postedfile.ContentLength

 '如果要上傳的文件不爲空
 If intImgSize <> 0 Then

  '如果大於8K, 則禁止上傳
  If intImgSize > 8000 Then
   Label1.Text = "圖片太大"
   Exit Sub
  End If

  '定義一個變量儲存用戶上傳圖片的文件類型
  Dim strImgType As String = postedfile.ContentType

  '只接受.gif格式的圖片
  Dim filesplit() As String = Split(strImgType, "/")
  strImgType = filesplit(filesplit.Length - 1)
  If strImgType <> "gif" Then
   Label1.Text = "圖片格式不對"
   Exit Sub
  End If


  '儲存要上傳的文件的整個路徑
  filesplit = Split(postedfile.FileName, "/")
  '取得上傳文件的文件名
  Dim filename As String = filesplit(filesplit.Length - 1)
  '將上傳的圖片保存到服務器當前目錄的headimg文件夾中
  postedfile.SaveAs(Server.MapPath("headimg") & "/" & filename)
  '定義一個變量儲存服務器上當前上傳圖片的路徑
  Dim imgpath As String = "headimg/" & filename
  img = "<img src=" & imgpath & " border=0>"

  '將圖片儲存到數據庫
  Dim scon As New SqlConnection("server=localhost;database=northwind;uid=sa;pwd=123")
  scon.Open()
  Dim scom As New SqlCommand("insert into users values (@img)", scon)
  scom.Parameters.Add("@img", SqlDbType.VarChar).Value = img
  Try
   scom.ExecuteNonQuery()
   Catch ex As Exception
  End Try
  scon.Close()
  '轉到查看圖片窗口
  Response.Redirect("ViewPicture.aspx")
 End If
End Sub
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章