Skip to main content

Menyimpan Data Tipe BLOB di MS Access

Seperti telah dijelaskan di posting terdahulu, BLOB atau Binary Large Object Bitmap merupakan tipe data biner yang digunakan untuk menyimpan objek berupa file ke dalam suatu database. Di MS Access kita juga bisa membuat sebuah database yang digunakan khusus untuk menyimpan objek berupa file. Ikuti caranya pada pembahasan berikut ini.

Untuk mudahnya, kita akan membuat sebuah database. Namailah database itu blob.accdb. Database blob.accdb ini hanya akan berisi sebuah tabel yang akan digunakan untuk mengelola data yang berupa file. apa pun tipe file nya. Oleh karena itu supaya database blob.accdb ini informatif, maka kita akan membuat sebuah tabel, sebutlah nama tabel itu tblBlob. Berikut ini adalah field beserta propertinya yang ada dalam tblBlob.
  1. Field Name: blobId
    1. Field Description: Nomor urut BLOB object
    2. Properti:
      1. Caption: BlobId
      2. Type: Long Integer (Autonumber)
  2. Field Name: blobObjek
    1. Field Description: Sisipkan sebuah objek BLOB di sini
    2. Properti:
      1. Caption: Objek BLOB
      2. Type: OLE Object
  3. Field Name: blobMeta
    1. Field Description: Metadata dari objek BLOB
    2. Properti:
      1. Caption: Meta Data
      2. Type: Text
  4. Field Name: blobNamaFile
    1. Field Description: Nama file orisinil dari objek BLOB
    2. Properti:
      1. Caption: Nama File
      2. Type: Text
  5. Field Name: blobNamaEkstensi
    1. Field Description: Nama ekstensi orisinil dari objek BLOB
    2. Properti:
      1. Caption: Nama Ekstensi
      2. Type: Text
  6. Field Name: blobUkuran
    1. Field Description: Ukuran file orisinil dari objek BLOB
    2. Properti:
      1. Caption: Ukuran
      2. Type: Long Integer (Number)
  7. Field Name: blobDeskripsi
    1. Field Description: Deskripsi ringkas dari objek BLOB
    2. Properti:
      1. Caption: Deskripsi
      2. Type: Text
Setelah tabel tblBlob beserta field yang ada di dalamnya selesai dibuat, langkah selanjutnya adalah membuat sebuah form. Untuk itu, sorotlah tblBlob lalu pilih tab Ribbon Create, dan buat sebuah form dengan menggunakan salah satu tombol yang ada di Group Forms. Pilih saja cara membuat form yang paling nyaman di antara tombol Form, Blank Form, Form Wizard, dan Form Design. Misalkan, kita menggunakan tombol Form. Hasilnya akan seperti ini:
Ikuti langkah-langkah di bawah ini:
  1. Simpanlah form yang baru saja dibuat dengan nama frmBlob.
  2. Hapuslah tipe form control Bound Object Frame yang bernama blobObjek.
  3. Sisipkan sebuah tipe control Image untuk mengganti Bound Object Frame dengan menekan tombol Image di Group Control. Properti control itu adalah sbb:
    1. Name=blobData
    2. Control Source= untuk sementara, control ini dikosongkan (unbound). Control Source ini akan diisi expression builder saat kita membahas cara membaca data tipe BLOB.
      Design view setelah pergantian control adalah sbb:
  4. Pada bagian Form Header, sisipkan sebuah text box control dan 2 buah tombol perintah. Propertinya adalah sbb:
    1. Text Box, Name= txtNameFile, label untuk text box ini, Caption=Upload File
    2. Button (Form Control), Name=cmdUpload, Caption=Upload File Baru
    3. Button (Form Control), Name=cmdPilihFile, Caption=Pilih File, Picture=Open Folder
  5. Pada bagian Form Footer, sisipkan beberapa tombol perintah berikut ini:
    1. Button (Form Control), Name=cmdSimpan, Caption=Simpan
    2. Button (Form Control), Name=cmdSimpanTambahBaru, Caption=Simpan, Tambah Data Baru
    3. Button (Form Control), Name=cmdTambahBaru, Caption=Tambah Data Baru
    4. Button (Form Control), Name=cmdHapus, Caption=Hapus
  6. Hapus semua properti Control Source yang terhubung (bound) ke tabel tblBlob sehingga semua Control Source tidak terisi atau Unbound. Jadi nama-nama control berikut ini tidak mempunyai nilai Control Source: blobId, blobMeta, blobNamaFile, blobNamaEkstensi, blobUkuran, dan blobDeskripsi. Selain itu, properti Record Source dari form frmBlob juga Unbound.
  7. Langkah terakhir, untuk melindungi metadata file dari pengeditan yang tidak perlu, aturlah properti Enabled=False untuk control berikut ini: blobId, blobMeta, blobNamaFile, blobNamaEkstensi, dan blobUkuran.
Design view dari frmBlob, setelah mengalami perubahan adalah sebagai berikut:

Selanjutnya, kita menuliskan kode VBA melalui modul. Ada dua modul yang harus dibuat. Modul yang pertama berkaitan dengan form frmBlob, yang merupakan class module. Sedangkan modul yang kedua merupakan standard module yang berisi kode VBA khusus untuk menyimpan data BLOB yang dilakukan melalui form frmBlob beserta class module Form_frmBlob. Kita beri nama standard module itu mdlBlob.
Berikut ini adalah kode VBA yang ada di form Form_frmBlob:
  1. Option Compare Database  
  2. Private Const constStrTableName As String = "tblBlob"  
  3. Private Const constPrimaryKeyFieldName As String = "blobId"  
  4. Private strLocalSql  As String  
  5.     
  6. Private Sub cmdHapus_Click()  
  7.   Dim strKriteria As Variant  
  8.   Dim strPesan As String  
  9.   strKriteria = Me.blobId  
  10.   strPesan = "Data dengan Id nomor " & strKriteria & " akan dihapus?"  
  11.   If MsgBox(strPesan, vbYesNo, "Hapus Data BLOB") = vbYes Then  
  12.     daoDbs.Execute "DELETE * FROM " & constStrTableName & " WHERE " & constPrimaryKeyFieldName & "=" & strKriteria  
  13.     MsgBox "Data dengan Id nomor " & strKriteria & " telah dihapus.", vbInformation  
  14.     Me.blobNamaFile = vbNullString  
  15.     Me.blobNamaEkstensi = vbNullString  
  16.     Me.blobUkuran = vbNullString  
  17.     Me.blobId = vbNullString  
  18.     Me.blobDeskripsi = vbNullString  
  19.     Me.blobMeta = vbNullString  
  20.     
  21.   End If  
  22. End Sub  
  23.     
  24. Private Sub cmdPilihFile_Click()  
  25.   Me.txtNamaFile = kotakFileDialog(Nz(Me.txtNamaFile, ""))  
  26.   Me.txtNamaFile.SetFocus  
  27. End Sub  
  28. Private Sub cmdSimpan_Click()  
  29.   Dim rs As DAO.Recordset  
  30.   Dim strKriteria As Variant  
  31.   Dim strSql As String  
  32.   Cancel = False  
  33.   If IsNull(Me.blobNamaFile) Then  
  34.     MsgBox "Tidak ada file yang disimpan.", vbExclamation  
  35.     Cancel = True  
  36.     Exit Sub  
  37.   End If  
  38.   strKriteria = Me.blobId  
  39.   strSql = strLocalSql & " WHERE " & constPrimaryKeyFieldName & "=" & strKriteria  
  40.   Set rs = daoDbs.OpenRecordset(strSql, dbOpenDynaset)  
  41.   rs.Edit  
  42.   rs!blobDeskripsi = Me.blobDeskripsi  
  43.   rs.Update  
  44.   rs.Close  
  45.   Set rs = Nothing  
  46. End Sub  
  47.     
  48. Private Sub cmdSimpanTambahBaru_Click()  
  49.   cmdSimpan_Click  
  50.   If Not Cancel Then cmdPilihFile_Click  
  51. End Sub  
  52.     
  53. Private Sub cmdTambahBaru_Click()  
  54.   cmdPilihFile_Click  
  55. End Sub  
  56.     
  57. Private Sub cmdUpload_Click()  
  58.   Dim rs As DAO.Recordset  
  59.   Dim strPathFile As String  
  60.   Dim oleBlobData As Variant  
  61.       
  62.   If IsNull(Me.txtNamaFile) Then  
  63.     MsgBox "Tidak ada nama file untuk di-upload.", vbExclamation  
  64.     Me.txtNamaFile.SetFocus  
  65.     Exit Sub  
  66.   End If  
  67.   If Me.txtNamaFile = "" _  
  68.     Or Not adaNamaFile(Me.txtNamaFile) Then  
  69.     MsgBox "Tidak ada nama file untuk di-upload.", vbExclamation  
  70.     Me.txtNamaFile.SetFocus  
  71.     Exit Sub  
  72.   End If  
  73.   Set rs = daoDbs.OpenRecordset(constStrTableName, dbOpenTable)  
  74.   rs.AddNew  
  75.   If CLng(simpanBlob(Me.txtNamaFile, rs, "blobObjek")) > constBlobMaxSize Then  
  76.     MsgBox "Ukuran file lebih besar dari yang dipersyaratkan.", vbExclamation  
  77.     Exit Sub  
  78.   End If  
  79.   oleBlobData = simpanBlob(Me.txtNamaFile, rs, "blobObjek")  
  80.   rs!blobNamaFile = uraiPathFile(Me.txtNamaFile)(0)  
  81.   rs!blobNamaEkstensi = uraiPathFile(Me.txtNamaFile)(2)  
  82.   rs!blobUkuran = CLng(oleBlobData)  
  83.   rs.Update  
  84.   rs.Bookmark = rs.LastModified  
  85.   Me.blobId = rs!blobId  
  86.       
  87.   If folderTemporer = "" Then Exit Sub  
  88.   strPathFile = folderTemporer & rs!blobNamaFile  
  89.   Me.blobNamaFile = rs!blobNamaFile  
  90.   Me.blobNamaEkstensi = rs!blobNamaEkstensi  
  91.   Me.blobUkuran = rs!blobUkuran  
  92.   Me.blobData.Requery  
  93.     
  94.   rs.Close  
  95.   Set rs = Nothing  
  96. End Sub  
  97.     
  98. Private Sub Form_Open(Cancel As Integer)  
  99.   strLocalSql = "SELECT * FROM " & constStrTableName  
  100.   Set daoDbs = CurrentDb()  
  101. End Sub  
Berikut ini adalah kode VBA yang ada di modul mdlBlob:
  1. Option Compare Database  
  2. Option Explicit  
  3. Const BlockSize = 32768  
  4. Const UNIQUE_NAME = &H0  
  5. Const constSeparatorCharacter As String = ","  
  6. Public Const constBlobMaxSize As Long = 20000000  
  7. Private Declare Function GetTempPathA Lib "kernel32" _  
  8.    (ByVal nBufferLength As Long, _  
  9.     ByVal lpBuffer As StringAs Long  
  10. Const dbOpenTable = DB_OPEN_TABLE  
  11. Const acSysCmdInitMeter = SYSCMD_INITMETER  
  12. Const acSysCmdUpdateMeter = SYSCMD_UPDATEMETER  
  13. Const acSysCmdRemoveMeter = SYSCMD_REMOVEMETER  
  14. Public daoDbs As DAO.Database  
  15.     
  16. Function simpanBlob(Source As String, T As Recordset, _  
  17. sField As StringAs Variant  
  18.   Dim intNumBlocks As Integer, intSourceFile As Integer, i As Integer  
  19.   Dim lngFileLength As Long, lngLeftOver As Long, lngFileSize As Long  
  20.   Dim strFileData As String  
  21.   Dim varRetVal As Variant  
  22.     
  23.   On Error GoTo Err_simpanBlob  
  24.     
  25.   intSourceFile = FreeFile  
  26.   Open Source For Binary Access Read As intSourceFile  
  27.     
  28.   lngFileLength = LOF(intSourceFile)  
  29.   If lngFileLength = 0 Or lngFileLength > constBlobMaxSize Then  
  30.       simpanBlob = lngFileLength  
  31.       Exit Function  
  32.   End If  
  33.     
  34.   intNumBlocks = lngFileLength \ BlockSize  
  35.   lngLeftOver = lngFileLength Mod BlockSize  
  36.       
  37.   varRetVal = SysCmd(acSysCmdInitMeter, "Reading BLOB", _  
  38.            lngFileLength \ 1000)  
  39.       
  40.   strFileData = String$(lngLeftOver, 32)  
  41.   Get intSourceFile, , strFileData  
  42.   T(sField).AppendChunk (strFileData)  
  43.     
  44.   varRetVal = SysCmd(acSysCmdUpdateMeter, lngLeftOver / 1000)  
  45.     
  46.   strFileData = String$(BlockSize, 32)  
  47.   For i = 1 To intNumBlocks  
  48.       Get intSourceFile, , strFileData  
  49.       T(sField).AppendChunk (strFileData)  
  50.     
  51.       varRetVal = SysCmd(acSysCmdUpdateMeter, BlockSize * i / 1000)  
  52.   Next i  
  53.     
  54.   varRetVal = SysCmd(acSysCmdRemoveMeter)  
  55.   Close intSourceFile  
  56.       
  57.   simpanBlob = lngFileLength  
  58.   Exit Function  
  59.     
  60. Err_simpanBlob:  
  61.   simpanBlob = -Err  
  62.   Exit Function  
  63.     
  64. End Function  
  65.     
  66. Function uraiPathFile(strFilePath As StringAs Variant  
  67.   Dim objFSO  As Object  
  68.   Set objFSO = CreateObject("Scripting.FileSystemObject")  
  69.   uraiPathFile = Array(objFSO.GetFileName(strFilePath), _  
  70.                         objFSO.GetBaseName(strFilePath), _  
  71.                         objFSO.GetExtensionName(strFilePath) _  
  72.                         )  
  73.                             
  74.   Set objFSO = Nothing  
  75. End Function  
  76.     
  77. Function buatFolderTemporer() As String  
  78.   Dim objFSO  As Object, objFolder  As Object  
  79.   Set objFSO = CreateObject("Scripting.FileSystemObject")  
  80.   Set objFolder = objFSO.createFolder(folderPathTemporer & "blob")  
  81.   Set objFolder = Nothing  
  82.   Set objFSO = Nothing  
  83. End Function  
  84.     
  85. Function folderTemporer() As String  
  86.   Dim strTempFolder As String  
  87.   Dim objFSO  As Object, objFolder  As Object  
  88.   Set objFSO = CreateObject("Scripting.FileSystemObject")  
  89.       
  90.   folderTemporer = ""  
  91.   If Not objFSO.FolderExists(folderPathTemporer & "blob"Then buatFolderTemporer  
  92.   strTempFolder = tambahkanBackslash(folderPathTemporer & "blob")  
  93.   folderTemporer = strTempFolder  
  94.   Set objFSO = Nothing  
  95. End Function  
  96.     
  97. Function tambahkanBackslash(s As StringAs String  
  98.   If Len(s) > 0 Then  
  99.     If Right$(s, 1) <> "\" Then  
  100.       tambahkanBackslash = s + "\"  
  101.     Else  
  102.       tambahkanBackslash = s  
  103.     End If  
  104.   Else  
  105.     tambahkanBackslash = "\"  
  106.   End If  
  107. End Function    
  108.     
  109. Function kotakFileDialog(Optional strFileName As String = ""Optional boolAllowMultiSelect As Boolean = FalseAs String  
  110. 'aktifkan Microsoft Office Object Library di Tools > References... (minimum versi 12.0)  
  111.   Dim fd As Office.FileDialog  
  112.   Dim vrtSelectedItem As Variant, itemFile() As String, i As Integer  
  113.       
  114.   Set fd = Application.FileDialog(msoFileDialogFilePicker)  
  115.       
  116.   With fd  
  117.     .AllowMultiSelect = boolAllowMultiSelect  
  118.     .Title = "Memilih File"  
  119.     .Filters.Clear  
  120.     .ButtonName = "Pilih"  
  121.     If .Show Then  
  122.       If .AllowMultiSelect Then  
  123.         ReDim Preserve itemFile(.SelectedItems.Count - 1)  
  124.         i = 0  
  125.         For Each vrtSelectedItem In .SelectedItems  
  126.           itemFile(i) = vrtSelectedItem  
  127.           i = i + 1  
  128.         Next vrtSelectedItem  
  129.         kotakFileDialog = Join(itemFile, ",")  
  130.       Else  
  131.         kotakFileDialog = .SelectedItems.Item(1)  
  132.       End If  
  133.     Else  
  134.       If strFileName <> "" Then kotakFileDialog = strFileName  
  135.     End If  
  136.   End With  
  137.   Set fd = Nothing  
  138. End Function  
  139.     
  140. Function adaNamaFile(strFileName As StringAs Boolean  
  141.     
  142.   Dim objFSO  As Object, objFolder  As Object  
  143.   Set objFSO = CreateObject("Scripting.FileSystemObject")  
  144.       
  145.   adaNamaFile = False  
  146.   If objFSO.FileExists(strFileName) Then adaNamaFile = True  
  147.   Set objFSO = Nothing  
  148. End Function  
  149.     
  150.     
  151. Function folderPathTemporer() As String  
  152.       
  153.   Dim objFSO  As Object  
  154.   Set objFSO = CreateObject("Scripting.FileSystemObject")  
  155.   folderPathTemporer = pathTemporer  
  156.   Set objFSO = Nothing  
  157. End Function  
  158.     
  159. Private Function pathTemporer() As String  
  160.       
  161.    Dim sTmp       As String  
  162.    Dim i          As Integer  
  163.     
  164.    i = GetTempPathA(0, "")  
  165.    sTmp = Space(i)  
  166.     
  167.    Call GetTempPathA(i, sTmp)  
  168.    pathTemporer = tambahkanBackslash(Left$(sTmp, i - 1))  
  169.      
  170. End Function  
Untuk memperoleh contoh aplikasi BLOB, silakan ikuti petunjuk di bawah ini:
  1. Ikuti blog Access Terapan di Facebook dengan mem-follow atau me-like FB page di https://www.facebook.com/AccessTerapan atau follow Google Blog Follower. 
  2. Kirim email ke admin yanto.e.subroto@gmail.com untuk diikutsertakan menjadi anggota grup Access Terapan. 
  3. Sebagai tanda bukti keanggotaan, admin grup Access Terapan akan mengirimkan email ke alamat yang dituju. 
  4. Selanjutnya, silakan download file blobSimpan.zip.File ini berisi 3 objek Access.
    1. Tabel yang bernama tblBlob, khusus untuk menyimpan data BLOB beserta properti/metadata
    2. Form yang bernama frmBlob, khusus untuk antarmuka antara user dengan tblBlob. Di dalamnya berisi class modul Frm_frmBlob.
    3. Modul yang bernama mdlBlob, digunakan untuk memporses upload file ke dalam database di tblBlob.
  5. Bukalah form frmBlob dalam format Form View.
  6. Sebagai uji coba lakukan upload file (apa saja terserah), yang penting tidak boleh melebihi batas maksimum ukuran file yang dipersyaratkan pada deklarasi konstanta Public Const constBlobMaxSize.

Comments

  1. sangat bermanfaat
    saya mencoba langkah demi langkah, tapi LongBinaryData yang tersimpan di OLE Object, ketika saya coba melakukan debug.print untuk melihat isinya, hasilnya bukan binary, tapi hasilnya seperti ini
    / ©Ë¨7¸ô¥ kSÍՍ ¾eÇ 8S....dst

    itu kenapa ya?
    mohon pencerahannya

    ReplyDelete
    Replies
    1. Itu kode biner kalau data ole didebug. Saat di form, data blob dapat berupa gambar atau hanya nama file. Untuk membukanya, harus menggunakan aplikasi yg didefault Windows.

      Delete

Post a Comment

Posting Terpopuler

Cara Mengatur dan Menggunakan ODBC untuk Mengakses Data Eksternal

Memahami Properti Validation Rule dan Validation Text pada Tabel di Access

Format Untuk Field Dengan Tipe Data Number dan Currency di MS Access