从Salesforce获取文件的base64数据 [英] Get base64 data of file from Salesforce

查看:132
本文介绍了从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数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆