UPLOAD
Daha sonra "UploadDownload.aspx" sayfanızı oluşturun. İçine bir FileUpload, Label ve bir Button ekleyin.
Private Sub Upload()
If BrowseUpload.PostedFile IsNot Nothing Then
Dim myFile As HttpPostedFile = BrowseUpload.PostedFile
Dim nFileLen As Integer = myFile.ContentLength
If nFileLen > 0 Then
Dim myData As Byte() = New Byte(nFileLen - 1) {}
myFile.InputStream.Read(myData, 0, nFileLen)
Dim strFilename As String = Path.GetFileName(myFile.FileName)
Dim nFileID As Integer = WriteToDB(strFilename, myFile.ContentType, myData)
End If
End If
End Sub
Private Function WriteToDB(ByVal strName As String, ByVal strType As String, ByRef Buffer As Byte()) As Integer
Dim nFileID As Integer = 0
Dim dbConn As New SqlConnection(ReturnConnstr)
Dim dbAdapt As New SqlDataAdapter("SELECT * FROM DOSYALAR", dbConn)
dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey
Dim dbCB As New SqlCommandBuilder(dbAdapt)
dbConn.Open()
Dim dbSet As New DataSet()
dbAdapt.Fill(dbSet, "DOSYALAR")
Dim dbTable As DataTable = dbSet.Tables("DOSYALAR")
Dim dbRow As DataRow = dbTable.NewRow()
dbRow("Name") = strName
dbRow("Size") = Buffer.Length
dbRow("Type") = strType
dbRow("Data") = Buffer
dbTable.Rows.Add(dbRow)
dbAdapt.Update(dbSet, "DOSYALAR")
If Not dbRow.IsNull("ID") Then
nFileID = CInt(dbRow("ID"))
End If
dbConn.Close()
End Function
Download işlemi için bize veritabanındaki kaydın ID'si gerekmektedir. Bunun için bir DataGrid oluşturup içini "DOSYALAR" tablosundaki veriler ile doldurun ( SELECT * FROM DOSYALAR ). Ben DevExpress componentini kullandığımdan DataGrid'e direkt link ekleyip işlemimi yapabiliyorum, siz de dosyanın ID'sini DataGrid içinde görüp fonksiyona parametre olarak gönderebilirsiniz.
Private Sub Download(ByVal key As Integer)
Dim nFileID As Integer = 0
Dim dbConn As New SqlConnection(ReturnConnstr)
Dim dbAdapt As New SqlDataAdapter("SELECT * FROM DOSYALAR WHERE ID =" & key, dbConn)
dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey
Dim dbCB As New SqlCommandBuilder(dbAdapt)
dbConn.Open()
Dim dbSet As New DataSet()
dbAdapt.Fill(dbSet, "DOSYALAR")
Dim dbTable As DataTable = dbSet.Tables("DOSYALAR")
Dim dbRow As DataRow = dbTable.Rows(0)
Dim buffer() As Byte
buffer = dbRow("Data")
Dim name As String = dbRow("Name")
Dim type As String = Mid(name, name.LastIndexOf(".") + 2)
name = Mid(name, 1, name.LastIndexOf("."))
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment;filename=" & name & "." & type)
Response.ContentType = "text/plain"
Response.BinaryWrite(buffer)
Response.End()
End Sub
Bu dosya upload ve download işlemleri bana çok kolaylık sağladı, umarım sizin de işinize yarayacaktır.
Kolay gelsin.

0 yorum:
Yorum Gönder