【问题标题】:How to download an image from Azure DevOps Services HTML Field using API如何使用 API 从 Azure DevOps Services HTML 字段下载图像
【发布时间】:2020-05-29 09:39:19
【问题描述】:

我想从我们的 Azure DevOps Services 实例下载工作项详细信息并将其推送到我们的本地 TFS 服务器。

我已经使用 C# 中的 WorkItemTrackingHttpClient 连接到 DevOps 服务器。 我可以遍历我找到的工作项,可以查看字段,使用 GetAttachmentContentAsync 下载附件。到目前为止一切顺利。

我需要完成的最后一个细节是复制/下载 HTML 描述字段中的嵌入图像。我可以从 HTML 字段中提取 HTML 代码,并在其中看到一个或多个 img src 行。

<img src=\"https://dev.azure.com/tenant/projectguid/_apis/wit/attachments/d928c8ee-f493-4d30-99a5-f62b7f36a2f7?fileName=grafik.png"\>

所有这些都有文件名 grafik.png,但 fileGuid 不同。

我尝试使用 GetAttachmentContentAsync 在此 guid 上下载,但没有成功。 我尝试使用普通 Stream 下载文件,但没有成功,我认为这是由于身份验证。 图像文件也不会显示为普通附件。

所以问题是,如何从我的 C# 客户端从 Azure DevOps 下载此图像,该图像通过 API 使用 PAT 进行身份验证。有没有我可以用来下载这个文件的 API 调用?我找不到它,或者我可以以某种方式使用该 PAT 对 WebClient 进行身份验证,以便它可以下载它?

【问题讨论】:

    标签: azure-devops


    【解决方案1】:

    经过进一步的故障排除,现在 GetAttachmentContentAsync 可以下载图像了。

    对于任何可能正在寻找类似解决方案的人。这就是我所做的

    用于下载的代码

    public string DownloadAttachment(string url, string fileName, int workItemId)

        {
            string[] urlSplit = url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            int index = urlSplit.Length - 1;
            Guid attGuid = new Guid(urlSplit[(index)]);
    
            if (fileName == string.Empty)
            {
                fileName = urlSplit[(index)] + ".png";
            }
            return DownloadAttachment(attGuid, fileName, workItemId);
        }
    
        public string DownloadAttachment(Guid attGuid, string fileName, int workItemId)
        {
            var credentials = new VssBasicCredential(string.Empty, this.personalAccessToken);
    
            // create instance of work item tracking http client
            using (var httpClient = new WorkItemTrackingHttpClient(this.uri, credentials))
            {
                Stream attStream = httpClient.GetAttachmentContentAsync(attGuid).Result;
    
                string folderPath = @"C:\Temp\WorkItemAttachments\" + workItemId;
                string fileFullPath = folderPath + "\\" + fileName;
                Directory.CreateDirectory(folderPath);
    
                using (FileStream writeStream = new FileStream(fileFullPath, FileMode.Create, FileAccess.ReadWrite))
                {
                    attStream.CopyTo(writeStream);
                }
            }
    
            return fileName;
    
        }
    

    【讨论】:

    • 感谢您在这里分享您的解决方案,请您接受您的解决方案作为答案吗?因此,对于遇到相同问题的其他成员轻松找到解决方案将很有帮助。祝你有美好的一天:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2020-05-12
    • 2019-09-03
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多