通过


在 Microsoft Dataverse 中使用文件列数据

Microsoft Dataverse 中的文件列不同于存储二进制数据的其他系统列,因为不能直接在创建或更新作中设置值,也不能使用记录检索文件数据。 若要为文件列创建、检索、更新或删除二进制数据,请使用本文中所述的方法。 了解如何使用 SDK for .NET 和 Web API 上传、下载和删除文件,包括对大型文件的分块传输的支持。

可以通过 Web API 使用多种不同的方法处理文件列数据。 所有方法均受支持,因此请选择最适合你的方法。 由于二进制文件可能很大,因此通常需要将文件拆分为多个区块(或块),以便按顺序或并行发送或接收,以提高性能。

文件名列

每个文件列都有一个支持的只读字符串列,其中包含文件的名称。 此列的架构名称与文件列的名称相同,但 _Name 追加到其中。 因此,如果架构名称为 sample_FileColumn,则支持字符串列为 sample_FileColumn_Name。 支持列的逻辑名称为 sample_filecolumn_name

注释

文件名列不会显示在 Power Apps 设计器中。

与 FileAttachment 表的关系

当您为某张表创建文件列时,也会在该表与 FileAttachment 表之间建立一个新的“一对多”关系。 关系的名称为 {table logical name}_FileAttachments. 例如,如果文件列是帐户表的一部分,则关系名称为 account_FileAttachments

可以使用此关系返回有关文件列和表的任何其他文件列的更多数据。 有关详细信息,请参阅检索记录的文件附加信息

检索过程中的行为

检索记录并包含文件列时,返回的值是文件的唯一标识符。 您可以使用此值通过 DeleteFile 消息删除该文件。 除了检查列是否具有值之外,此 ID 没有其他用途。 有关详细信息,请参阅 使用 DeleteFile 消息

以下示例展示了从文件列检索数据时可预期的结果,其操作方式与其他列相同。

这些示例检索帐户记录中的 name 列、sample_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

详细信息:

检索与记录相关的文件的额外信息

可以使用文件列表和 FileAttachment 表之间的关系返回与该表行关联的所有文件列的相关信息。

RetrieveAccountRecordWithFileData静态方法演示如何返回有关包含与具有匹配account值的记录相关的accountid数据的所有文件列的信息。

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"]}");
        });
}

输出

在此示例中,account 表中有一个名为 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

详细信息:

上传文件

可以通过三种不同的方式将文件上传到文件列:

  • 使用可用于 SDK 和 Web API 的 Dataverse 消息
  • 使用 Web API 在单个请求中上传文件
  • 使用 Web API 以区块方式上传文件

注释

  • 验证列最大文件大小是否足够大,以接受正在上传的文件。 有关详细信息,请参阅 “检查最大文件大小”。
  • 还可以使用这些 API 上传图像列数据。 有关详细信息,请参阅 “使用图像列数据”。

使用 Dataverse 消息上传文件

可以通过使用用于 .NET 或 Web API 的 SDK 来使用 Dataverse 的消息。 这样上传文件需要使用一组三条消息:

消息 说明
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;

}

详细信息:

注释

此示例方法包括一些逻辑,用于尝试使用 FileExtensionContentTypeProvider.TryGetContentType(String, String) 方法获取文件的 MIME 类型(如果未提供)。 如果未找到该类型,则将其设置为application/octet-stream

使用 Web API 在单个请求中上传文件

如果文件大小小于 128 MB,则可以使用 Web API 在单个请求中上传该文件。

以下示例将名为 4094kb.txt 的文本文件上传至 account 表中名为 sample_filecolumn 的文件列,该表中 accountid 等于 <accountid> 的记录。

请求

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

在单个请求中上传文件的 PowerShell 示例

以下 PowerShell Set-FileColumn 函数演示如何使用 Web API 在单个请求中上传文件。

若要详细了解如何将 PowerShell 和 Visual Studio Code 与 Dataverse Web API 配合使用,请参阅:

此函数需要一个能够设置全局 $baseURI$baseHeaders 的连接。 使用 ConnectCreate a Connect 函数中所述的函数设置这些值。

<#
.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 以区块形式上传文件,请使用以下一组请求。

以下示例将名为 25mb.pdf 的 PDF 文件上传到 account 表中名为 sample_filecolumn 的文件列,该表中 accountid 等于 <accountid> 的记录。

请求

第一个请求必须包含以下标头: 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

响应 位置 标头包括用于后续请求的 URL。 它包括一个 sessiontoken 查询参数,该参数指示使用它发送的所有请求都是同一作的一部分。

响应包括以下标头。

Header 说明
x-ms-chunk-size 提供建议的区块大小(以字节为单位)。
Accept-Ranges 指示服务器支持客户端的部分请求,用于文件下载。 该值 bytes 指示后续请求中的范围值应以字节为单位。
Access-Control-Expose-Headers 指示 x-ms-chunk-size 标头值应提供给浏览器中运行的脚本,以响应跨源请求。

请求

后续请求应使用第一个请求返回的 Location 标头的值,以便 sessiontoken 包含该值。

每个请求必须在请求主体中包含该部分文件,并包含以下标头:

Header 说明
x-ms-file-name 文件的名称。
内容类型 设置为 application/octet-stream
Content-Range (内容范围) 使用此格式:
<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
Content-Length 指示消息的大小。 在前面的示例中,最后一个请求的此值是704546而不是4194304
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$baseHeaders,并使用在创建连接函数中描述的Connect函数。

<#
.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.");
   }
}

详细信息:

下载文件

可以使用三种不同的方法从文件列下载文件:

  • 使用可用于 SDK 和 Web API 的 Dataverse 消息
  • 使用 Web API 在单个请求中下载文件
  • 使用 Web API 以区块方式下载文件

注释

还可以使用这些方法来下载图像列,但存在一些差异。 有关详细信息,请参阅 “下载映像”。

对于本地环境或环境使用 自管理密钥(BYOK)时,该文件不在文件存储中。 当文件不在文件存储中时,不支持在多个区块中下载。 InitializeFileBlocksDownloadResponse ComplexTypeInitializeFileBlocksDownloadResponse 类具有一个IsChunkingSupported属性,指示文件是否可以在多个区块中下载。 如果不支持分块,该值 BlockLength 将设置为文件大小。

如果 IsChunkingSupported 设置为 false 时尝试下载部分数据块,将会导致此错误:

名称:UploadingAndDownloadingInMultipleChunksNotSupported
代码:0x80090017
消息:Downloading in multiple chunks isn't supported for the files stored in the database.

使用 Dataverse 消息下载文件

可以通过使用用于 .NET 或 Web API 的 SDK 来使用 Dataverse 消息。 这样下载文件需要使用两条消息:

消息 说明
InitializeFileBlocksDownload 使用此消息指定要从中下载文件的列。 它返回文件大小(以字节为单位)和 文件继续标记 ,可用于使用 DownloadBlock 消息在块中下载文件。
DownloadBlock 请求块大小、偏移量值以及文件延续令牌。

下载所有块后,必须将它们联接在一起,以创建整个下载的文件。

可以使用如下所示的函数通过 SDK 和 InitializeFileBlocksDownloadRequestDownloadBlockRequest 类下载文件或映像。

/// <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 在单个请求中下载文件

以下示例从 account 表中名称为 sample_filecolumn 的文件列下载名为 4094kb.txt 的文本文件,该表中 accountid 等于 <accountid> 的记录。

请求

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

响应:

响应包括以下标头。

Header 说明
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 以区块形式下载文件,请使用以下一组请求。

以下示例将名为 25mb.pdf 的 PDF 文件下载到 account 表中名称为 sample_filecolumn 的文件列,该表中 accountid 等于 <accountid> 的记录。

请求

请使用 Range 标头,并采用以下格式来指定要返回的字节数:
<unit>=<range-start>-<range-end>
其中unit表示字节,range-start对于第一个请求是0

在获取响应标头告知文件大小的第一个响应 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

响应:

响应包括以下标头:

Header 说明
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. >

删除文件

可以使用以下任一方法删除文件列中的文件:

  • 使用可用于 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 请求来删除文件。

以下示例将删除 account 表中 sample_filecolumn 列中 accountid 等于 <accountid> 的记录对应的文件数据。

请求

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

详细信息: 删除单个属性值

另请参阅

文件和映像概述
列数据类型 > 文件列
使用代码处理文件列定义
示例:使用适用于 .NET 的 Dataverse SDK 进行文件操作
示例:使用 Dataverse Web API 的文件操作