次の方法で共有


ファイル列のデータを使用する

ファイル列は、バイナリ データを格納できる他のシステム列とは異なり、作成または更新操作で値を直接設定したり、レコードでファイル データを取得したりすることはできません。 ファイル列のバイナリ データを作成、取得、更新、または削除するには、この記事で説明されているメソッドを使用する必要があります。

Web API を使用してファイル列データを操作するには、いくつかの方法があります。 すべての方法が同等にサポートされています。 使いやすい方法を選択してください。 バイナリ ファイルはサイズが大きいため、複数のチャンク (ブロック) に分割し、順次または並列に送受信することでパフォーマンスを向上させる必要がある傾向が高いです。

ファイル名列

各ファイル列には、ファイル名を含む読み取り専用の文字列列がサポートされています。 この列のスキーマ名は、ファイル列と同じ名前ですが、_Name が付加されています。 したがって、スキーマ名が sample_FileColumn、サポート文字列列は sample_FileColumn_Name になります。 サポート列の論理名は sample_filecolumn_name となります。

注意

Power Apps デザイナーでファイル名の列は表示されません。

FileAttachment テーブルへのリレーションシップ

あるテーブルにファイル列が作成されると、そのテーブルと FileAttachment テーブルの間に新しい一対多の関係が作成されます。 関連付けの名前は {table logical name}_FileAttachments です。 たとえば、ファイル列が account テーブルの一部である場合、関連付けの名は account_FileAttachments となります。

この関係を使用して、テーブルのファイル列およびその他のファイル列に関する追加データを返すことができます。 詳細情報: レコードのファイルに関する追加情報を取得する

取得時の挙動

レコードを検索してファイル列を含めると、返される値はそのファイルに固有の識別子になります。 この値を使用して、DeleteFile メッセージでファイルを削除することができます。 列に値があるかどうかを確認する以外に、この ID を使用する方法はありません。 詳しくは、DeleteFile メッセージを使用するを参照してください。

次の例は、ファイル列からデータを取得する際に、他の列と同様に期待できる内容を示しています。

次の例では、アカウント レコードの namesample_filecolumn、および sample_filecolumn_name 列を取得します。

static void RetrieveAccountRecordWithFileColumns(
    IOrganizationService service,
    Guid accountid) 
{

   Entity account = service.Retrieve(
         "account", 
         accountid, 
         new ColumnSet("name", "sample_filecolumn", "sample_filecolumn_name"));

   Console.WriteLine($"name: {account["name"]}");
   Console.WriteLine($"sample_filecolumn: {account["sample_filecolumn"]}");
   Console.WriteLine($"sample_filecolumn_name: {account["sample_filecolumn_name"]}");
}

出力:

name: Contoso Ltd.
sample_filecolumn: <file id>
sample_filecolumn_name: 25mb.pdf

注意

ファイル ID を返すには、列を明示的に要求する必要があります。クエリで ColumnSet.AllColumns を true にすると、ファイル列は返されません。 new ColumnSet(true) を使用した場合上記の関数では、結果は System.Collections.Generic.KeyNotFoundException になります。

詳細情報:

レコードのファイルに関する追加情報を取得する

ファイル列テーブルと FileAttachment テーブルの関係を利用して、そのテーブル行に関連するすべてのファイル列に関する情報を返すことができます。

RetrieveAccountRecordWithFileData 静的メソッドは、一致する accountid 値を持つ account レコードに関連するデータを含むすべてのファイル列の情報が表示されます。

static void RetrieveAccountRecordWithFileData(
    IOrganizationService service, 
    Guid accountid)
{
    // Create query for related records
    var relationshipQueryCollection = new RelationshipQueryCollection {
        {
            new Relationship("account_FileAttachments"),
            new QueryExpression("fileattachment"){
                ColumnSet = new ColumnSet(
                                "createdon",
                                "mimetype",
                                "filesizeinbytes",
                                "filename",
                                "regardingfieldname",
                                "fileattachmentid")
            }
        }
    };

    // Include the related query with the Retrieve Request
    RetrieveRequest request = new RetrieveRequest
    {
        ColumnSet = new ColumnSet("accountid"),
        RelatedEntitiesQuery = relationshipQueryCollection,
        Target = new EntityReference("account", accountid)
    };

    // Send the request
    RetrieveResponse response = (RetrieveResponse)service.Execute(request);

    //Display related FileAttachment data for the account record
    response.Entity.RelatedEntities[new Relationship("account_FileAttachments")]
        .Entities.ToList().ForEach(e =>
        {
            Console.WriteLine($"createdon: {e.FormattedValues["createdon"]}");
            Console.WriteLine($"mimetype: {e["mimetype"]}");
            Console.WriteLine($"filesizeinbytes: {e.FormattedValues["filesizeinbytes"]}");
            Console.WriteLine($"filename: {e["filename"]}");
            Console.WriteLine($"regardingfieldname: {e["regardingfieldname"]}");
            Console.WriteLine($"fileattachmentid: {e["fileattachmentid"]}");
        });
}

出力:

この場合、アカウント テーブルには sample_filecolumn という名前のファイル列がひとつあり、その列に格納されているファイルに関するデータです。

createdon: 10/22/2022 2:01 PM
mimetype: application/pdf
filesizeinbytes: 25,870,370
filename: 25mb.pdf
regardingfieldname: sample_filecolumn
fileattachmentid: 63a6afb7-4c52-ed11-bba1-000d3a9933c9

詳細情報:

ファイルのアップロード

ファイル列にファイルをアップロードするには、次の 3 つの方法があります。

  • SDK と Web API の両方で利用可能な Dataverse メッセージを使用する
  • Web API を使用して 1 回のリクエストでファイルをアップロードする
  • Web API を使用してファイルをチャンクでアップロードする

注意

  • 列の最大ファイル サイズが、アップロードするファイルを受け入れるのに十分な大きさであるかどうかを確認する必要があります。 詳細情報は、最大ファイルサイズを確認するをご確認ください。
  • これらの API を使用して、イメージ列データをアップロードすることもできます。 詳細: イメージ列データを使用する

Dataverse メッセージを使用してをファイルをアップロードする

SDK for .NET または Web API を使用して Dataverse メッセージを使用することができます。 この方法でファイルをアップロードするには、次の 3 つのメッセージのセットを使用する必要があります:

Message 説明設定
InitializeFileBlocksUpload このメッセージを使用して、ファイルをアップロードする列を示します。 UploadBlock メッセージを使用して、CommitFileBlocksUpload と一緒にブロック単位でファイルをアップロードするのに使える ファイル継続トークン を返します。
UploadBlock ファイルをブロックに分割し、各ブロックに blockid を生成します。 続いて、すべてのブロックがファイル継続トークンとともに送信されるまで、何度も要求を行います。
CommitFileBlocksUpload UploadBlock を使用してすべてのブロックに対するリクエストを送信した後、このメッセージを使用して、送信によるアップロード操作をコミットします。
- 生成された blockids の一覧
- ファイルの名前
- ファイルの MIME タイプ
- ファイルの継続トークン

InitializeFileBlocksUploadRequestUploadBlockRequestCommitFileBlocksUploadRequest の各クラスを使用してファイルやイメージをアップロードするには、以下のような関数を使用することができます。

/// <summary>
/// Uploads a file or image column value
/// </summary>
/// <param name="service">The service</param>
/// <param name="entityReference">A reference to the record with the file or image column</param>
/// <param name="fileAttributeName">The name of the file or image column</param>
/// <param name="fileInfo">Information about the file or image to upload.</param>
/// <param name="fileMimeType">The mime type of the file or image, if known.</param>
/// <returns></returns>
static Guid UploadFile(
         IOrganizationService service,
         EntityReference entityReference,
         string fileAttributeName,
         FileInfo fileInfo,
         string fileMimeType = null)
{

   // Initialize the upload
   InitializeFileBlocksUploadRequest initializeFileBlocksUploadRequest = new()
   {
         Target = entityReference,
         FileAttributeName = fileAttributeName,
         FileName = fileInfo.Name
   };

   var initializeFileBlocksUploadResponse =
         (InitializeFileBlocksUploadResponse)service.Execute(initializeFileBlocksUploadRequest);

   string fileContinuationToken = initializeFileBlocksUploadResponse.FileContinuationToken;

   // Capture blockids while uploading
   List<string> blockIds = new();

   using Stream uploadFileStream = fileInfo.OpenRead();

   int blockSize = 4 * 1024 * 1024; // 4 MB

   byte[] buffer = new byte[blockSize];
   int bytesRead = 0;

   long fileSize = fileInfo.Length;
   // The number of iterations that will be required:
   // int blocksCount = (int)Math.Ceiling(fileSize / (float)blockSize);
   int blockNumber = 0;

   // While there is unread data from the file
   while ((bytesRead = uploadFileStream.Read(buffer, 0, buffer.Length)) > 0)
   {
         // The file or final block may be smaller than 4MB
         if (bytesRead < buffer.Length)
         {
            Array.Resize(ref buffer, bytesRead);
         }

         blockNumber++;

         string blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()));

         blockIds.Add(blockId);

         // Prepare the request
         UploadBlockRequest uploadBlockRequest = new()
         {
            BlockData = buffer,
            BlockId = blockId,
            FileContinuationToken = fileContinuationToken,
         };

         // Send the request
         service.Execute(uploadBlockRequest);
   }

   // Try to get the mimetype if not provided.
   if (string.IsNullOrEmpty(fileMimeType))
   {
         var provider = new FileExtensionContentTypeProvider();

         if (!provider.TryGetContentType(fileInfo.Name, out fileMimeType))
         {
            fileMimeType = "application/octet-stream";
         }
   }

   // Commit the upload
   CommitFileBlocksUploadRequest commitFileBlocksUploadRequest = new()
   {
         BlockList = blockIds.ToArray(),
         FileContinuationToken = fileContinuationToken,
         FileName = fileInfo.Name,
         MimeType = fileMimeType
   };

   var commitFileBlocksUploadResponse =
         (CommitFileBlocksUploadResponse)service.Execute(commitFileBlocksUploadRequest);

   return commitFileBlocksUploadResponse.FileId;

}

詳細情報:

注意

この関数には、ファイルの MIME タイプが提供されない場合に、FileExtensionContentTypeProvider.TryGetContentType(String, String) メソッドを使用してその MIME タイプを取得するロジックが含まれています。 種類が見つからない場合、application/octet-stream に設定されます。

Web API を使用して 1 回のリクエストでファイルをアップロードする

ファイル サイズが 128 MB 未満の場合、Web API を使用して 1 回の要求でファイルをアップロードすることができます。

次の例は、accountid<accountid> と等しいレコードに対して、4094kb.txt という名前のテキストファイルを account テーブルの sample_filecolumn という名前のファイル列にアップロードします。

要求:

PATCH [Organization Uri]/api/data/v9.2/accounts(<accountid>)/sample_filecolumn HTTP/1.1
OData-MaxVersion: 4.0
OData-Version: 4.0
If-None-Match: null
Accept: application/json
Content-Type: application/octet-stream
x-ms-file-name: 4094kb.txt
Content-Length: 4191273

< binary content removed for brevity>

応答:

HTTP/1.1 204 NoContent
OData-Version: 4.0

1 回の要求でファイルをアップロードする PowerShell の例

次の PowerShell Set-FileColumn 関数は、Web API を使用して単一の要求でファイルをアップロードする方法を示します。

PowerShell と Visual Studio Code と Dataverse Web API の使用について解説します:

この関数には、接続関数の作成で説明されている、グローバル $baseURI を設定する接続と、Connect 関数を使用して設定する$baseHeaders が必要です。

<#
.SYNOPSIS
Sets a column value for a file in a specified table.

.DESCRIPTION
The Set-FileColumn function sets a column value for a file in a specified table. 
It uses a single request and can work with files less than 128 MB.

.PARAMETER setName
The entity set name of the table where the file is stored.

.PARAMETER id
The unique identifier of record.

.PARAMETER columnName
The logical name of the file column to set the value for.

.PARAMETER file
The path to the file to upload.

.EXAMPLE
Set-FileColumn `
   -setName 'accounts' `
   -id [System.Guid]::New('12345678-1234-1234-1234-1234567890AB') `
   -columnName 'new_filecolumn' `
   -file 'C:\Path\To\File.txt'
   
Sets the value of the 'new_filecolumn' column for the file with the specified ID 
in the account table to the contents of the File.txt file.

#>
function Set-FileColumn {
   param (
      [Parameter(Mandatory)]
      [string]
      $setName,
      [Parameter(Mandatory)]
      [System.Guid]
      $id,
      [Parameter(Mandatory)]
      [string]
      $columnName,
      [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
      [System.IO.FileInfo]$file
   )

   $uri = '{0}{1}({2})/{3}' -f $baseURI, $setName, $id, $columnName

   $patchHeaders = $baseHeaders.Clone()
   $patchHeaders.Add('Content-Type', 'application/octet-stream')
   $patchHeaders.Add('x-ms-file-name', $file.Name)

   $body = [System.IO.File]::ReadAllBytes($file.FullName)

   $FileUploadRequest = @{
      Uri     = $uri
      Method  = 'Patch'
      Headers = $patchHeaders
      Body    = $body
   }

   Invoke-RestMethod @FileUploadRequest
}

Web API を使用してファイルをチャンクでアップロードする

Web API を使用してファイルをチャンクでアップロードするには、次の一連の要求を使用します。

次の例は、accountid<accountid> と等しいレコードに対して、25mb.pdf という名前の PDF ファイルを account テーブルの sample_filecolumn という名前のファイル列にアップロードします。

要求:

最初のリクエストには、次のヘッダーを含める必要があります: x-ms-transfer-mode: chunked

x-ms-file-name クエリ パラメータでファイル名を設定します。

PATCH [Organization Uri]/api/data/v9.2/accounts(<accountid>)/sample_filecolumn?x-ms-file-name=25mb.pdf HTTP/1.1
x-ms-transfer-mode: chunked
OData-MaxVersion: 4.0
OData-Version: 4.0
If-None-Match: null
Accept: application/json

注意

ファイル名は x-ms-file-name リクエスト ヘッダとして含めることもできますが、この場合、ASCII 文字セット以外のファイル名には対応しません。 ヘッダーが使用された場合、x-ms-file-name クエリパラメータよりも優先されます。

応答:

HTTP/1.1 200 OK
Accept-Ranges: bytes
Location: [Organization Uri]/api/data/v9.2/accounts(<accountid>)/sample_filecolumn?sessiontoken=<sessiontoken value removed for brevity>
OData-Version: 4.0
x-ms-chunk-size: 4194304
Access-Control-Expose-Headers: x-ms-chunk-size

応答の Location ヘッダーには、以降のリクエストで使用する URL が含まれています。 それを使って送信されたすべてのリクエストが同じ操作の一部であることを示す sessiontoken クエリ パラメータが含まれています。

この応答には、次のヘッダーが含まれています。

ヘッダー 説明設定
x-ms-chunk-size 推奨されるチャンク サイズをバイト単位で提供します。
受け入れのレンジ サーバーが、ファイルのダウンロードに関するクライアントからの部分的な要求をサポートしていることを示します。 bytes は、それ以降の要求における範囲の値がバイト単位であることを示します。
Access-Control-Expose-Headers クロスオリジン リクエストに応答して、ブラウザ上で動作するスクリプトが x-ms-chunk-size ヘッダ値を利用できるようにすることを示します。

要求:

後続のリクエストでは、sessiontoken の値が含まれるように、最初のリクエストで返された Location ヘッダーの値を使用する必要があります。

各リクエストは、ファイルのその部分を本文に含み、以下のヘッダを含む必要があります。

ヘッダー 説明設定
x-ms-file-name ファイルの名前。
Content-Type application/octet-stream に設定
コンテンツ範囲 このフォーマットを使用して以下のことが可能になります:
<unit> <range-start>-<range-end>/<size>
最初のリクエストの値: bytes 0-4194303/25870370 測定がバイトを使用していることを示します。 この要求には、25870370 バイト (約 25 MB) の大きさのファイルの最初の 4194303 バイトが含まれています。
ファイル全体が送信されるまで、後続の各リクエストでこの値が増加します。
bytes 4194304-8388607/25870370
bytes 8388608-12582911/25870370
bytes 12582912-16777215/25870370
bytes 16777216-20971519/25870370
bytes 20971520-25165823/25870370
bytes 25165824-25870369/25870370
コンテンツの長さ メッセージのサイズを表します。 上記の例では、最後のリクエストに対するこの値は 4194304 ではなく 704546 となります。
PATCH [Organization Uri]/api/data/v9.2/accounts(<accountid>)/sample_filecolumn?sessiontoken=<sessiontoken value removed for brevity> HTTP/1.1
x-ms-file-name: 25mb.pdf
OData-MaxVersion: 4.0
OData-Version: 4.0
If-None-Match: null
Accept: application/json
Content-Type: application/octet-stream
Content-Range: bytes 0-4194303/25870370
Content-Length: 4194304

< byte[] content removed for brevity>

部分的なコンテンツを含む各リクエストに対して、レスポンスは 206 PartialContent となります。

応答:

HTTP/1.1 206 PartialContent
OData-Version: 4.0

ファイルの最後のチャンクを含む最終リクエストの場合、レスポンスは 204 NoContent となります。

応答:

HTTP/1.1 204 NoContent
OData-Version: 4.0

ファイルをチャンクでアップロードする PowerShell の例

次の PowerShell Set-FileColumnInChunks 関数は、チャンクでファイルをアップロードする方法を示します。 この関数には、接続関数の作成で説明されている、グローバル $baseURI を設定する接続と、Connect 関数を使用して設定する$baseHeaders が必要です。

<#
.SYNOPSIS
Sets a column value for a file in a specified table.

.DESCRIPTION
The Set-FileColumnInChunks function sets a column value for a file in a specified table. 
It uses chunked file upload to efficiently upload large files.

.PARAMETER setName
The name of the table where the file is stored.

.PARAMETER id
The unique identifier of record.

.PARAMETER columnName
The logical name of the file column to set the value for.

.PARAMETER file
The path to the file to upload.

.EXAMPLE
Set-FileColumnInChunks `
   -setName 'accounts' `
   -id [System.Guid]::New('12345678-1234-1234-1234-1234567890AB') `
   -columnName 'new_filecolumn' `
   -file 'C:\Path\To\File.txt'
   
Sets the value of the 'new_filecolumn' column for the file with the specified ID in the account table to the contents of the File.txt file.

#>
function Set-FileColumnInChunks {
   param (
      [Parameter(Mandatory)]
      [string]
      $setName,
      [Parameter(Mandatory)]
      [System.Guid]
      $id,
      [Parameter(Mandatory)]
      [string]
      $columnName,
      [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
      [System.IO.FileInfo]$file
   )

   $uri = '{0}{1}({2})' -f $baseURI, $setName, $id
   $uri += '/{0}?x-ms-file-name={1}' -f $columnName, $file.Name

   $chunkHeaders = $baseHeaders.Clone()
   $chunkHeaders.Add('x-ms-transfer-mode', 'chunked')

   $InitializeChunkedFileUploadRequest = @{
      Uri     = $uri
      Method  = 'Patch'
      Headers = $chunkHeaders
   }

   Invoke-RestMethod @InitializeChunkedFileUploadRequest `
      -ResponseHeadersVariable rhv

   $locationUri = $rhv['Location'][0]
   $chunkSize = [int]$rhv['x-ms-chunk-size'][0]

   $bytes = [System.IO.File]::ReadAllBytes($file.FullName)

   for ($offset = 0; $offset -lt $bytes.Length; $offset += $chunkSize) {
         
      $count = if (($offSet + $chunkSize) -gt $bytes.Length) 
                  { $bytes.Length % $chunkSize } 
               else { $chunkSize }
      
      $lastByte = $offset + ($count - 1)

      $range = 'bytes {0}-{1}/{2}' -f $offset, $lastByte, $bytes.Length

      $contentHeaders = $baseHeaders.Clone()
      $contentHeaders.Add('Content-Range', $range)
      $contentHeaders.Add('Content-Type', 'application/octet-stream')
      $contentHeaders.Add('x-ms-file-name', $file.Name)

      $UploadFileChunkRequest = @{
         Uri     = $locationUri
         Method  = 'Patch'
         Headers = $contentHeaders
         Body    = [byte[]]$bytes[$offSet..$lastByte]
      }

      Invoke-RestMethod @UploadFileChunkRequest
   }
}

最大ファイル サイズの確認

ファイルをアップロードする前に、ファイルのサイズが MaxSizeInKB プロパティに保存されている設定された 最大ファイルサイズ を超えているかどうかを確認することができます。

大きすぎるファイルをアップロードしようとすると、次のエラーが発生します:

名前: unManagedidsattachmentinvalidfilesize
コード: 0x80044a02
番号: -2147202558
メッセージ: Attachment file size is too big.

次の例を使用して、最大ファイル サイズを確認できます:

静的な GetFileColumnMaxSizeInKb メソッドは、ファイル列の MaxSizeInKB 値を返します。

/// <summary>
/// Retrieves the MaxSizeInKb property of a file column.
/// </summary>
/// <param name="service">IOrganizationService</param>
/// <param name="entityLogicalName">The logical name of the table that has the column</param>
/// <param name="fileColumnLogicalName">The logical name of the file column.</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static int GetFileColumnMaxSizeInKb(
    IOrganizationService service, 
    string entityLogicalName, 
    string fileColumnLogicalName) 
{

   RetrieveAttributeRequest retrieveAttributeRequest = new() { 
         EntityLogicalName = entityLogicalName,
         LogicalName = fileColumnLogicalName
   };

   RetrieveAttributeResponse retrieveAttributeResponse;
   try
   {
         retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
   }
   catch (Exception)
   {
         throw;
   }

   if (retrieveAttributeResponse.AttributeMetadata is FileAttributeMetadata fileColumn)
   {
         return fileColumn.MaxSizeInKB.Value;
   }
   else
   {
         throw new Exception($"{entityLogicalName}.{fileColumnLogicalName} is not a file column.");
   }
}

詳細情報:

ファイルのダウンロード

ファイル列からファイルをダウンロードするためには 3 つの異なる方法があります。

  • SDK と Web API の両方で利用可能な Dataverse メッセージを使用する
  • Web API を使用して 1 回のリクエストでファイルをダウンロードする
  • Web API を使用してファイルをチャンクでダウンロードする

注意

これらの方法はイメージ列のダウンロードにも使用できますが、違いがいくつかあります。 詳細: イメージをダウンロードする

オンプレミス環境の場合、または環境で セルフ マネージド キー (BYOK) が使用されている場合、ファイルはファイル ストレージにありません。 ファイルがファイル ストレージにない場合、複数のチャンクでのダウンロードはサポートされません。 InitializeFileBlocksDownloadResponse ComplexTypeInitializeFileBlocksDownloadResponse Class には、ファイルが複数の塊でダウンロードできるかどうかを示す IsChunkingSupported プロパティがあります。 チャンク化がサポートされていない場合は、ファイルサイズに BlockLength を設定します。

IsChunkingSupported が false に設定されているときに部分チャンクをダウンロードしようとすると、次のエラーが発生します。

名前: UploadingAndDownloadingInMultipleChunksNotSupported
コード: 0x80090017
メッセージ: Downloading in multiple chunks is not supported for the files stored in the database.

Dataverse メッセージを使用してをファイルをダウンロードする

SDK for .NET または Web API を使用して Dataverse メッセージを使用することができます。 この方法でファイルをダウンロードするには、次のメッセージを使用する必要があります:

Message 説明設定
InitializeFileBlocksDownload このメッセージを使用して、ファイルをダウンロードする列を示します。 これは、バイト単位のファイル サイズと、DownloadBlock メッセージを使ってブロック単位でファイルをダウンロードする際に使用するファイル継続トークンを返します。
DownloadBlock ブロックのサイズ、オフセット値、ファイル継続トークンを要求します。

すべてのブロックをダウンロードしたら、それらを結合して、ダウンロードしたファイル全体を作成する必要があります。

InitializeFileBlocksDownloadRequest クラスと DownloadBlockRequest クラスを使って SDK でファイルやイメージをダウンロードするには、次のような関数を使用します。

/// <summary>
/// Downloads a file or image
/// </summary>
/// <param name="service">The service</param>
/// <param name="entityReference">A reference to the record with the file or image column</param>
/// <param name="attributeName">The name of the file or image column</param>
/// <returns></returns>
private static byte[] DownloadFile(
            IOrganizationService service,
            EntityReference entityReference,
            string attributeName)
{
   InitializeFileBlocksDownloadRequest initializeFileBlocksDownloadRequest = new()
   {
         Target = entityReference,
         FileAttributeName = attributeName
   };

   var initializeFileBlocksDownloadResponse =
         (InitializeFileBlocksDownloadResponse)service.Execute(initializeFileBlocksDownloadRequest);

   string fileContinuationToken = initializeFileBlocksDownloadResponse.FileContinuationToken;
   long fileSizeInBytes = initializeFileBlocksDownloadResponse.FileSizeInBytes;

   List<byte> fileBytes = new((int)fileSizeInBytes);

   long offset = 0;
   // If chunking is not supported, chunk size will be full size of the file.
   long blockSizeDownload = !initializeFileBlocksDownloadResponse.IsChunkingSupported ? fileSizeInBytes :  4 * 1024 * 1024;

   // File size may be smaller than defined block size
   if (fileSizeInBytes < blockSizeDownload)
   {
         blockSizeDownload = fileSizeInBytes;
   }

   while (fileSizeInBytes > 0)
   {
         // Prepare the request
         DownloadBlockRequest downLoadBlockRequest = new()
         {
            BlockLength = blockSizeDownload,
            FileContinuationToken = fileContinuationToken,
            Offset = offset
         };

         // Send the request
         var downloadBlockResponse =
                  (DownloadBlockResponse)service.Execute(downLoadBlockRequest);

         // Add the block returned to the list
         fileBytes.AddRange(downloadBlockResponse.Data);

         // Subtract the amount downloaded,
         // which may make fileSizeInBytes < 0 and indicate
         // no further blocks to download
         fileSizeInBytes -= (int)blockSizeDownload;
         // Increment the offset to start at the beginning of the next block.
         offset += blockSizeDownload;
   }

   return fileBytes.ToArray();
}

詳細情報:

Web API を使用して 1 回のリクエストでファイルをダウンロードする

次の例は、accountid<accountid> と等しいレコードに対して、4094kb.txt という名前のテキストファイルを account テーブルの sample_filecolumn という名前のファイル列からダウンロードします。

要求:

GET [Organization Uri]/api/data/v9.2/accounts(<accountid>)/sample_filecolumn/$value HTTP/1.1
OData-MaxVersion: 4.0
OData-Version: 4.0
If-None-Match: null
Accept: application/json

応答:

この応答には、次のヘッダーが含まれています。

ヘッダー 説明
x-ms-file-size ファイルのサイズをバイト単位で指定します。
x-ms-file-name ファイルの名前。
mimetype ファイルの MIME タイプ
Access-Control-Expose-Headers クロスオリジンリクエストに応答して、ブラウザ上で動作するスクリプトが x-ms-file-sizex-ms-file-namemimetype ヘッダ値を利用できるようにすることを示します。
HTTP/1.1 200 OK
x-ms-file-size: 4191273
x-ms-file-name: 4094kb.txt
mimetype: text/plain
Access-Control-Expose-Headers: x-ms-file-size; x-ms-file-name; mimetype

< byte[] content removed for brevity. >

Web API を使用してファイルをチャンクでダウンロードする

注意

以下の例は、IsChunkingSupported が true に設定されている場合の例です。 false の場合は、Web API を使用して単一のリクエストでファイルをダウンロードする を使用してください。

Web API を使用してファイルをチャンクでダウンロードするには、次の一連の要求を使用します。

次の例は、accountid<accountid> と等しいレコードに対して、25mb.pdf という名前の PDF ファイルを account テーブルの sample_filecolumn という名前のファイル列にダウンロードします。

要求:

このフォーマットを使って返すバイト数を指定するには、レンジ ヘッダを使用する:
<unit>=<range-start>-<range-end>
ここで unit はバイトで、最初のリクエストの range-start0 です。

ファイル全体をダウンロードするために何回繰り返す必要があるかは、x-ms-file-size 応答ヘッダでファイル サイズがわかる最初の応答を得るまでわかりません。

<range-start> がファイルの総サイズより小さい間は、後続のリクエストごとに <range-start><range-end> を増やし、ファイルの次のチャンクをリクエストします。

GET [Organization Uri]/api/data/v9.2/accounts(<accountid>)/sample_filecolumn/$value HTTP/1.1
Range: bytes=0-4194303
OData-MaxVersion: 4.0
OData-Version: 4.0
If-None-Match: null
Accept: application/json

応答:

この応答には、次のヘッダーが含まれています:

ヘッダー Description
x-ms-file-size ファイルのサイズをバイト単位で指定します。
x-ms-file-name ファイルの名前。
x-ms-chunk-size 推奨されるチャンク サイズをバイト単位で提供します。
mimetype ファイルの MIME タイプ
Access-Control-Expose-Headers クロスオリジン リクエストに応答して、ブラウザ上で動作するスクリプトが x-ms-file-sizex-ms-file-namex-ms-chunk-sizemimetype ヘッダ値を利用できるようにすることを示します。
HTTP/1.1 206 PartialContent
x-ms-file-size: 25870370
x-ms-file-name: 25mb.pdf
x-ms-chunk-size: 4194304
mimetype: application/pdf
Access-Control-Expose-Headers: x-ms-file-size; x-ms-file-name; x-ms-chunk-size; mimetype
OData-Version: 4.0

< byte[] content removed for brevity. >

ファイルを削除する

ファイル列にファイルを削除するには、次の 2 つの方法があります。

  • SDK と Web API の両方で利用可能な Dataverse DeleteFile メッセージを使用する
  • レコードのファイル列に対して、Web API を使用して DELETE リクエストを送信します。

DeleteFile メッセージの使用

CommitFileBlocksUploadResponse.FileId から返されたユニークな識別子、または 取得時の挙動 で説明されているように列から取得した識別子を使用して、DeleteFile メッセージでファイルを削除することができます。

以下のような関数を使って、DeleteFileRequest クラス を使用したユニークな識別子でファイルを削除することができます。

static Guid DeleteFile(IOrganizationService service, Guid fileId)
{
   DeleteFileRequest deleteFileRequest = new()
   {
      FileId = fileId
   };
   service.Execute(deleteFileRequest);
}

ファイル列に DELETE リクエストを送信する

Web API では、ファイルリソースの場所に DELETE リクエストを送信することで、ファイルを削除することができます。

次の例は、accountid<accountid> と等しいレコードの account テーブルの sample_filecolumn という列のファイル データを削除するものです。

要求:

DELETE [Organization Uri]/api/data/v9.2/accounts(<accountid>)/sample_filecolumn HTTP/1.1
OData-MaxVersion: 4.0
OData-Version: 4.0
If-None-Match: null
Accept: application/json

応答:

HTTP/1.1 204 NoContent
OData-Version: 4.0

詳細情報: 単一のプロパティ値を削除する

関連情報

ファイルおよび画像の概要
列のデータは他 > ファイル列
コードを使ってファイル列定義を操作する
サンプル: Dataverse SDK for .NET を使用したファイル操作
サンプル: Dataverse Web API を使用したファイル操作

注意

ドキュメントの言語設定についてお聞かせください。 簡単な調査を行います。 (この調査は英語です)

この調査には約 7 分かかります。 個人データは収集されません (プライバシー ステートメント)。