微软 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
如果你觉得有用的话,就留个赞吧!蟹蟹

相关推荐
脑袋大大的1 分钟前
判断当前是否为钉钉环境
开发语言·前端·javascript·钉钉·企业应用开发
Wy. Lsy29 分钟前
Kotlin基础学习记录
开发语言·学习·kotlin
Tanecious.1 小时前
C++--红黑树
开发语言·c++
Top`1 小时前
Java 泛型 (Generics)
java·开发语言·windows
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ2 小时前
如何使用Java WebSocket API实现客户端和服务器端的通信?
java·开发语言·websocket
Shartin2 小时前
Can201-Introduction to Networking: Application Layer应用层
服务器·开发语言·php
共享家95272 小时前
linux_线程概念
linux·开发语言·jvm
apihz3 小时前
VM虚拟机全版本网盘+免费本地网络穿透端口映射实时同步动态家庭IP教程
android·服务器·开发语言·网络·数据库·网络协议·tcp/ip
tanyongxi664 小时前
C++ Map 和 Set 详解:从原理到实战应用
开发语言·c++
干净的坏蛋4 小时前
Microsoft Word 中 .doc 和 .docx 的区别
microsoft·word