本文介绍了从 Salesforce 获取文件的 base64 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 Salesforce 获取机会文件并将它们复制到某个文件夹.我正在使用 .NET 库 连接到 Salesforcre.我可以获得我想要的任何数据,除了 [ContentVersion] 表中的 [VersionData] 字段,它包含我想要的文件的 base64 数据.我可以使用 Workbench 工具获取数据,但我通过 .NET 库获得的唯一内容是文件链接.我可以使用适当的标头创建 HttpClient 并调用该 URL,但我不喜欢这样做.我可以通过 .NET 库获取文件吗?

I need to get opportunity files from Salesforce and copy them to some folder. I am using .NET library for connecting to Salesforcre. I can get any data I want, except the [VersionData] field in [ContentVersion] table, which contains base64 data of the files I want. I can get the data with Workbench tool, but the only thing I get via .NET library is a link to file. I could create HttpClient with appropriate headers and invoke that URL, but I don't like to go this ways. Can I get the file via .NET library?

推荐答案

这是我的解决方案(模型类、端点方法、身份验证方法):

Here is my solution (model class, endpoint method, authentication method):

    public class ContentVersion
    {
        [JsonIgnoreSerialization]
        [JsonProperty("Id", NullValueHandling = NullValueHandling.Ignore)]
        public string Id { get; set; }

        [JsonProperty("ContentDocumentId")]
        public string ContentDocumentId { get; set; }

        [JsonProperty("FileExtension")]
        public string FileExtension { get; set; }

        [JsonProperty("Title")]
        public string Title { get; set; }

        [JsonProperty("VersionNumber")]
        public int VersionNumber { get; set; }

        [JsonProperty("IsLatest")]
        public bool IsLatest { get; set; }

        [JsonProperty("VersionData")]
        public string VersionDataURL { get; set; }

        public Stream VersionDataStream { get; set; }
    }

    public async Threading.Task<ContentVersion> GetContentNewestVersion(string EntityId)
    {
        // Authenticate if not already
        if (client == null) await Authenticate();

        // Create query string
        string query = @"SELECT
            Id,
            ContentDocumentId,
            FileExtension,
            Title,
            VersionNumber,
            IsLatest,
            VersionData
            FROM ContentVersion
            WHERE ContentDocumentId = '" + EntityId + "'";

        List<ContentVersion> results = new List<ContentVersion>();
        QueryResult<ContentVersion> queryResult = await client.QueryAsync<ContentVersion>(query);
        results.AddRange(queryResult.Records);
        while (!queryResult.Done)
        {
            queryResult = await client.QueryContinuationAsync<ContentVersion>(queryResult.NextRecordsUrl);
            results.AddRange(queryResult.Records);
        }

        // get only the newest Content version
        ContentVersion latestContentVersion = results.Where(r => r.IsLatest).OrderByDescending(r => r.VersionNumber).FirstOrDefault();

        // Get file stream via returned URL
        using (HttpClient httpClient = new HttpClient())
        {
            // Add access token to request
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);

            // call server
            var response = await httpClient.GetAsync(InstanceUrl + latestContentVersion.VersionDataURL);

            // read stream and append it to object
            latestContentVersion.VersionDataStream = await response.Content.ReadAsStreamAsync();
        }
        return latestContentVersion;
    }

    protected async Threading.Task Authenticate()
    {
        // Check if not already connected
        if (client == null)
        {
            // Security settings
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // Create Auth client
            var auth = new AuthenticationClient();

            // Authorize user
            await auth.UsernamePasswordAsync(LoginDetails.ClientId, LoginDetails.ClientSecret, LoginDetails.Username, LoginDetails.Password, LoginDetails.TokenRequestEndpoint);
            _instanceURL = auth.InstanceUrl;
            AccessToken = auth.AccessToken;

            // Create and return client with session variables
            client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
        }
    }

这就是我将收到的流写入文件的方式.

And this is how I write recieved stream to file.

    // deisred folder
    string PathToFolder = @"C:\destination\";

    // get stream from Salesforce
    ContentVersion documentContent = await forceAPI.GetContentNewestVersion(contentDocumentlink.ContentDocumentId);

    // write file from stream
    using (FileStream file = new FileStream(PathToFolder + documentContent.Title + "." + documentContent.FileExtension, FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        documentContent.VersionDataStream.CopyTo(file);
    }

这篇关于从 Salesforce 获取文件的 base64 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 22:28