2010年9月25日 星期六

Fileupload 上傳

Dim FileSplit() As String = Split(Me.FileUpload1.FileName, ".")
Dim nx As String = FileSplit(FileSplit.Length - 1)'取得檔案副檔名

Dim fileName As String = Now.ToString("yyyyMMdd")'取得日期
Dim ano As Int16 = (101) '流水號預設值
Dim Path As String = Server.MapPath("~/UpFile/")
Do While File.Exists(Path & fileName & ano & "." & nx) '判斷是否有相同檔名存在並累加流水編號
ano = ano + 1
Loop

Dim cn As New Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim strsql As String = "Insert Into database (filelink) values (@url)"
Dim cmd As New Data.SqlClient.SqlCommand(strsql, cn)


Dim FileOk As Boolean = False '宣告一個FileOk用來判別是否上傳成功,預設為False
Dim fileExtension As String '宣告一個變數存放檔案格式(副檔名)
Dim i As Integer
If Me.FileUpload1.HasFile Then '透過HasFile判斷有檔案上傳
fileExtension = IO.Path.GetExtension(Me.FileUpload1.FileName).ToLower '取得檔案格式
Dim allowedExtensions As String() = {".jpg", ".jpeg", ".png", ".gif", ".pdf"} '定義允許的檔案格式
For i = 0 To allowedExtensions.Length - 1 '逐一檢查允許的格式中是否有上傳的格式
If fileExtension = allowedExtensions(i) Then
FileOk = True
End If
Next
If FileOk Then
Try

Me.FileUpload1.PostedFile.SaveAs(Path & fileName & ano & "." & nx) '將上傳的檔案儲存
Me.Label1.Text = "Upload Success!!" '傳回成功

cn.Open()
cmd.Parameters.Add("@url", System.Data.SqlDbType.VarChar).Value = "~/UpFile/" & fileName & ano & "." & nx
cmd.ExecuteNonQuery()

cn.Close()

Catch ex As Exception
Me.Label1.Text = "Upload False!!
" + ex.Message
End Try
Else
Me.Label1.Text = "檔案上傳失敗,請確認檔案格式是否正確!!"
End If

End If

沒有留言:

張貼留言