微软 Power Apps MDA 模型驱动应用解决Image字段查询出来缩略图问题变原图方法(c#+Plugin方式)

微软 Power Apps MDA 模型驱动应用解决Image字段查询出来缩略图问题变原图方法(c#+Plugin方式)

在某些特定的场景中,需要将Image字段中的图片取出来,一般来说直接查询这个字段可以直接取,取出来的就是一个Base64格式的图片,但是我发现非常模糊,经了解是一个缩略图,那么如何将原图取出来的,其实微软官方文档也给出了解决方案。

链接: 微软官方文档链接入口

原图和缩略图的差别还是很大

直接贴代码

csharp 复制代码
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace testAction
{
    public class testplugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            var tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);

            if (context.MessageName.Equals("update", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity target)
                    {
                        var entity = service.Retrieve("new_modeldata", target.Id,
                            new ColumnSet("new_modeldataid", "new_name", "new_fabricimagebase64", "new_onedriveimage", "new_fabricimage", "new_image_url"));

                        // 直接将文件转换成Base64字符串,确保下载的是原图
                        string base64String = ConvertFileToBase64(service, entity, "new_fabricimage");

                        // 如果需要将base64保存回CRM记录
                        entity["new_fabricimagebase64"] = base64String;
                        service.Update(entity);
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException($"Error: {ex.Message}", ex);
                }
            }
        }

        // 将文件下载并转换成Base64字符串
        public string ConvertFileToBase64(IOrganizationService service, Entity entity, string fileAttributeName)
        {
            // 使用 InitializeFileBlocksDownloadRequest 确保获取的是原图
            InitializeFileDownload(service, entity, fileAttributeName, out string downloadToken, out long fileSize, out string fileName);
            return DownloadFileAsBase64(service, entity, downloadToken, fileSize);
        }

        private void InitializeFileDownload(IOrganizationService service, Entity entity, string fileAttributeName, out string token, out long fileSize, out string fileName)
        {
            var request = new InitializeFileBlocksDownloadRequest
            {
                Target = entity.ToEntityReference(),
                FileAttributeName = fileAttributeName
            };

            var response = service.Execute(request);
            token = (string)response.Results["FileContinuationToken"];
            fileSize = (long)response.Results["FileSizeInBytes"];
            fileName = (string)response.Results["FileName"];
        }

        // 将下载的文件块拼接并转换成Base64字符串
        private string DownloadFileAsBase64(IOrganizationService service, Entity entity, string downloadToken, long fileSize)
        {
            long offset = 0;
            const long chunkSize = 4 * 1024 * 1024; // 4MB
            int chunksCount = (int)(fileSize / chunkSize) + 1;
            byte[] fileBytes = new byte[fileSize];

            for (int chunkNumber = 0; chunkNumber < chunksCount; chunkNumber++)
            {
                var downloadRequest = new DownloadBlockRequest
                {
                    FileContinuationToken = downloadToken,
                    Offset = offset,
                    BlockLength = Math.Min(chunkSize, fileSize - offset)
                };

                var response = service.Execute(downloadRequest);
                byte[] chunkData = (byte[])response.Results["Data"];
                Buffer.BlockCopy(chunkData, 0, fileBytes, (int)offset, chunkData.Length);

                offset += chunkSize;
            }

            // 将字节数组转换为Base64字符串
            return Convert.ToBase64String(fileBytes);
        }
    }
}

ConvertFileToBase64 方法:

该方法负责下载文件并将其转换成 Base64 字符串。

它调用 InitializeFileDownload 来初始化文件下载操作,获取文件的下载令牌、文件大小和文件名。

InitializeFileDownload 方法:

这是初始化文件下载的关键步骤,使用 InitializeFileBlocksDownloadRequest 请求来确保获取完整文件。

该方法返回文件的下载令牌 (FileContinuationToken)、文件大小 (FileSizeInBytes)、文件名 (FileName),这些信息随后用于实际的下载操作。

DownloadFileAsBase64 方法:

该方法负责逐块(每块 4MB)下载文件的内容,并将其拼接成一个完整的字节数组。

下载完成后,将整个字节数组转换为 Base64 字符串并返回。

其中 DownloadBlockRequest 请求用于每次下载一块数据,逐步填充 fileBytes 字节数组。

好喽,这样就可以在代码中拿到原图了!

感谢大佬指正 小Monkey
如果你觉得有用的话,就留个赞吧!蟹蟹

相关推荐
自身就是太阳31 分钟前
Maven的高级特性
java·开发语言·数据库·后端·spring·maven
hakesashou37 分钟前
ruby和python哪个好学
开发语言·python·ruby
林一怂儿42 分钟前
H5 three.js 实现六年级观察物体
开发语言·javascript
NiNg_1_2341 小时前
Python协程详解
开发语言·python
黑白子20001 小时前
python定时任务,定时爬取水质和天气
开发语言·python
9ilk1 小时前
【与C++的邂逅】--- C++的IO流
开发语言·c++
是小满满满满吗1 小时前
C++中的继承
开发语言·c++·python
程序猿练习生1 小时前
C++速通LeetCode简单第16题-买卖股票的最佳时机
开发语言·c++·leetcode
OEC小胖胖1 小时前
js进阶-作用域是什么
开发语言·前端·javascript·ecmascript·web
只对您心动1 小时前
【QT】实现TCP服务器,客户端之间的通信
linux·服务器·c语言·开发语言·c++·qt·tcp/ip