Numéro d'article: 103257 - Dernière mise à jour: jeudi 18 janvier 2007 - Version: 2.3

ACC : Lecture, stockage et écriture Binary Large Objects (BLOB)

A noterCet article s'applique à un système d'exploitation différent de celui que vous utilisez. Le contenu de l'article qui ne vous concerne peut-être pas est désactivé.
Avancé : La nécessité de codage expert, l'interopérabilité et compétences multi-utilisateur.

Agrandir tout | Réduire tout

Résumé

Vous pouvez stocker des objets de données de grande taille (tels que les données audio, vidéo ou graphiques) dans un champ avec le type de données objet OLE dans une table Microsoft Access. Certains objets de données binaires de grande taille ne peut pas être représentées, toutefois, s'ils ne disposent pas d'un serveur OLE qui comprend des données stockées. Vous pouvez également stocker des copies des fichiers de programme exécutable ou d'autres données non-OLE dans une table Microsoft Access. Ce type de données est appelé une image bitmap objet binaire volumineux (BLOB).

Cet article suppose que vous êtes familiarisé avec Visual Basic pour applications et la création d'applications de Microsoft Access à l'aide des outils de programmation fournis avec Microsoft Access. Pour plus d'informations sur Visual Basic pour applications, reportez-vous à votre version du manuel «Création d'applications avec Microsoft Access».

Remarque : Visual Basic pour applications est appelé Access Basic dans Microsoft Access versions 1.x et 2.0. Pour plus d'informations sur Access Basic, consultez le manuel «Introduction à la programmation» dans Microsoft Access version 1.x ou le manuel «Création d'applications» dans Microsoft Access version 2.0.

Plus d'informations

L'exemple suivant contient deux exemples fonctions définies par l'utilisateur que vous pouvez utiliser pour gérer de grandes quantités de données binaires dans un champ avec le type de données objet OLE. Les fonctions définies par l'utilisateur sont ReadBLOB() et WriteBLOB().

  • La fonction ReadBLOB() lit un fichier binaire du disque et la stocke dans un champ objet OLE.
  • Les écritures de fonction WriteBLOB() données binaires stockées dans un objet OLE de champ dans un fichier sur disque.
Cet exemple montre comment copier un fichier binaire dans un champ objet OLE, puis comment écrire régulariser vers un nouveau fichier de disque :

  1. Créez un nouveau module appelé BLOB et entrez les lignes suivantes dans la section des déclarations du module :
    Option explicite
    BlockSize const = 32768
    Remarque : Si vous travaillez avec Microsoft Access 2.0, vous devrez également inclure les définitions suivantes après les deux précédents :
          Const dbOpenTable = DB_OPEN_TABLE
          Const acSysCmdInitMeter = SYSCMD_INITMETER
          Const acSysCmdUpdateMeter = SYSCMD_UPDATEMETER
          Const acSysCmdRemoveMeter = SYSCMD_REMOVEMETER
  2. Entrez le code suivant dans le module.

    Remarque : Dans l'exemple de code suivant, un trait de soulignement (_) à la fin d'une ligne est utilisé comme un caractère de continuation de ligne. Supprimez le trait de soulignement de fin de la ligne lors de la reprogrammation dans Access Basic.

    Remarque : Il est possible que la technique suivante ne fonctionnera pas pour Microsoft Access 1.x. Pour Microsoft Access 1.x, vous devrez peut-être modifier le code afin qu'il utilise des variables table au lieu de variables d'objet Recordset et l'OuvrirTable fonction au lieu de OpenRecordset.
          '**************************************************************
          ' FUNCTION: ReadBLOB()
          '
          ' PURPOSE:
          '   Reads a BLOB from a disk file and stores the contents in the
          '   specified table and field.
          '
          ' PREREQUISITES:
          '   The specified table with the OLE object field to contain the
          '   binary data must be opened in Visual Basic code (Access Basic
          '   code in Microsoft Access 2.0 and earlier) and the correct record
          '   navigated to prior to calling the ReadBLOB() function.
          '
          ' ARGUMENTS:
          '   Source - The path and filename of the binary information
          '            to be read and stored.
          '   T      - The table object to store the data in.
          '   Field  - The OLE object field in table T to store the data in.
          '
          ' RETURN:
          '   The number of bytes read from the Source file.
          '**************************************************************
          Function ReadBLOB(Source As String, T As Recordset, _
          sField As String)
              Dim NumBlocks As Integer, SourceFile As Integer, i As Integer
              Dim FileLength As Long, LeftOver As Long
              Dim FileData As String
              Dim RetVal As Variant
    
              On Error GoTo Err_ReadBLOB
    
              ' Open the source file.
              SourceFile = FreeFile
              Open Source For Binary Access Read As SourceFile
    
              ' Get the length of the file.
              FileLength = LOF(SourceFile)
              If FileLength = 0 Then
                  ReadBLOB = 0
                  Exit Function
              End If
    
              ' Calculate the number of blocks to read and leftover bytes.
              NumBlocks = FileLength \ BlockSize
              LeftOver = FileLength Mod BlockSize
    
              ' SysCmd is used to manipulate status bar meter.
              RetVal = SysCmd(acSysCmdInitMeter, "Reading BLOB", _
                       FileLength \ 1000)
    
              ' Put the record in edit mode.
              T.Edit
    
              ' Read the leftover data, writing it to the table.
              FileData = String$(LeftOver, 32)
              Get SourceFile, , FileData
              T(sField).AppendChunk (FileData)
    
              RetVal = SysCmd(acSysCmdUpdateMeter, LeftOver / 1000)
    
              ' Read the remaining blocks of data, writing them to the table.
              FileData = String$(BlockSize, 32)
              For i = 1 To NumBlocks
                  Get SourceFile, , FileData
                  T(sField).AppendChunk (FileData)
    
                  RetVal = SysCmd(acSysCmdUpdateMeter, BlockSize * i / 1000)
              Next i
    
              ' Update the record and terminate function.
              T.Update
              RetVal = SysCmd(acSysCmdRemoveMeter)
              Close SourceFile
              ReadBLOB = FileLength
              Exit Function
    
          Err_ReadBLOB:
              ReadBLOB = -Err
              Exit Function
    
          End Function
    
          '**************************************************************
          ' FUNCTION: WriteBLOB()
          '
          ' PURPOSE:
          '   Writes BLOB information stored in the specified table and field
          '   to the specified disk file.
          '
          ' PREREQUISITES:
          '   The specified table with the OLE object field containing the
          '   binary data must be opened in Visual Basic code (Access Basic
          '   code in Microsoft Access 2.0 or earlier) and the correct
          '   record navigated to prior to calling the WriteBLOB() function.
          '
          ' ARGUMENTS:
          '   T           - The table object containing the binary information.
          '   sField      - The OLE object field in table T containing the
          '                 binary information to write.
          '   Destination - The path and filename to write the binary
          '                 information to.
          '
          ' RETURN:
          '   The number of bytes written to the destination file.
          '**************************************************************
          Function WriteBLOB(T As Recordset, sField As String, _
          Destination As String)
              Dim NumBlocks As Integer, DestFile As Integer, i As Integer
              Dim FileLength As Long, LeftOver As Long
              Dim FileData As String
              Dim RetVal As Variant
    
              On Error GoTo Err_WriteBLOB
    
              ' Get the size of the field.
              FileLength = T(sField).FieldSize()
              If FileLength = 0 Then
                  WriteBLOB = 0
                  Exit Function
              End If
    
              ' Calculate number of blocks to write and leftover bytes.
              NumBlocks = FileLength \ BlockSize
              LeftOver = FileLength Mod BlockSize
    
              ' Remove any existing destination file.
              DestFile = FreeFile
              Open Destination For Output As DestFile
              Close DestFile
    
              ' Open the destination file.
              Open Destination For Binary As DestFile
    
              ' SysCmd is used to manipulate the status bar meter.
              RetVal = SysCmd(acSysCmdInitMeter, _
              "Writing BLOB", FileLength / 1000)
    
              ' Write the leftover data to the output file.
              FileData = T(sField).GetChunk(0, LeftOver)
              Put DestFile, , FileData
    
              ' Update the status bar meter.
              RetVal = SysCmd(acSysCmdUpdateMeter, LeftOver / 1000)
    
              ' Write the remaining blocks of data to the output file.
              For i = 1 To NumBlocks
                  ' Reads a chunk and writes it to output file.
                  FileData = T(sField).GetChunk((i - 1) * BlockSize _
                     + LeftOver, BlockSize)
                  Put DestFile, , FileData
    
                  RetVal = SysCmd(acSysCmdUpdateMeter, _
                  ((i - 1) * BlockSize + LeftOver) / 1000)
              Next i
    
              ' Terminates function
              RetVal = SysCmd(acSysCmdRemoveMeter)
              Close DestFile
              WriteBLOB = FileLength
              Exit Function
    
          Err_WriteBLOB:
              WriteBLOB = -Err
              Exit Function
    
          End Function
    
          '**************************************************************
          ' SUB: CopyFile
          '
          ' PURPOSE:
          '   Demonstrates how to use ReadBLOB() and WriteBLOB().
          '
          ' PREREQUISITES:
          '   A table called BLOB that contains an OLE Object field called
          '   Blob.
          '
          ' ARGUMENTS:
          '   Source - The path and filename of the information to copy.
          '   Destination - The path and filename of the file to write
          '                 the binary information to.
          '
          ' EXAMPLE:
          '   CopyFile "c:\windows\winfile.hlp", "c:\windows\winfil_1.hlp"
          '**************************************************************
          Sub CopyFile(Source As String, Destination As String)
              Dim BytesRead As Variant, BytesWritten As Variant
              Dim Msg As String
              Dim db As Database
              Dim T As Recordset
    
              ' Open the BLOB table.
              Set db = CurrentDb()
              Set T = db.OpenRecordset("BLOB", dbOpenTable)
    
              ' Create a new record and move to it.
              T.AddNew
              T.Update
              T.MoveLast
    
              BytesRead = ReadBLOB(Source, T, "Blob")
    
              Msg = "Finished reading """ & Source & """"
              Msg = Msg & Chr$(13) & ".. " & BytesRead & " bytes read."
              MsgBox Msg, 64, "Copy File"
    
              BytesWritten = WriteBLOB(T, "Blob", Destination)
    
              Msg = "Finished writing """ & Destination & """"
              Msg = Msg & Chr$(13) & ".. " & BytesWritten & " bytes written."
              MsgBox Msg, 64, "Copy File"
          End Sub
    						
  3. Créez la table suivante et enregistrez-la en tant que BLOB :
          Table: BLOB
          ------------------------
          Field Name: Blob
             Data Type: OLE Object
  4. À l'aide du module BLOB ouvert en mode Création, cliquez sur fenêtre Débogage (ou fenêtre immédiat dans Microsoft Access 2.0 ou version antérieure) dans le menu Affichage.
  5. Tapez la ligne suivante dans la fenêtre Débogage, et appuyez sur ENTRÉE :
          CopyFile "c:\windows\winfile.hlp", "c:\windows\winfil_1.hlp"
Les fonctions ReadBLOB() et WriteBLOB() copier le fichier d'aide Microsoft Windows dans le champ BLOB dans la table BLOB, puis à partir de là, un fichier de disque appelé Winfil_1.hlp

Les informations contenues dans cet article s'appliquent au(x) produit(s) suivant(s):
  • Microsoft Access 1.0 Standard
  • Microsoft Access 1.1 Standard
  • Microsoft Access 2.0 Standard
  • Microsoft Access 95 Standard
  • Microsoft Access 97 Standard
Mots-clés : 
kbmt kbinfo kbprogramming KB103257 KbMtfr
Traduction automatiqueTraduction automatique
IMPORTANT : Cet article est issu du système de traduction automatique mis au point par Microsoft (http://support.microsoft.com/gp/mtdetails). Un certain nombre d?articles obtenus par traduction automatique sont en effet mis à votre disposition en complément des articles traduits en langue française par des traducteurs professionnels. Cela vous permet d?avoir accès, dans votre propre langue, à l?ensemble des articles de la base de connaissances rédigés originellement en langue anglaise. Les articles traduits automatiquement ne sont pas toujours parfaits et peuvent comporter des erreurs de vocabulaire, de syntaxe ou de grammaire (probablement semblables aux erreurs que ferait une personne étrangère s?exprimant dans votre langue !). Néanmoins, mis à part ces imperfections, ces articles devraient suffire à vous orienter et à vous aider à résoudre votre problème. Microsoft s?efforce aussi continuellement de faire évoluer son système de traduction automatique.
La version anglaise de cet article est la suivante: 103257  (http://support.microsoft.com/kb/103257/en-us/ )
L'INFORMATION CONTENUE DANS CE DOCUMENT EST FOURNIE PAR MICROSOFT SANS GARANTIE D'AUCUNE SORTE, EXPLICITE OU IMPLICITE. L'UTILISATEUR ASSUME LE RISQUE DE L'UTILISATION DU CONTENU DE CE DOCUMENT. CE DOCUMENT NE PEUT ETRE REVENDU OU CEDE EN ECHANGE D'UN QUELCONQUE PROFIT.
Retired KB ArticleExclusion de responsabilité concernant les contenus obsolètes dans la Base de connaissances
Cet article concerne des produits pour lesquels Microsoft n'offre plus de support. Il est par conséquent fourni « en l'état » et ne sera plus mis à jour.