【问题标题】:Attachment uploaded to Azure devops through Rest api is not opening通过 Rest api 上传到 Azure devops 的附件未打开
【发布时间】:2020-12-01 14:56:32
【问题描述】:

您好,我已关注 Microsoft Doccument 并上传附件 devops 并成功将其附加到工作项。但是当我从devops userinteface文件下载文件时,显示但无法打开它。 这是代码

将 Iformfile 对象转换为二进制文件,谢谢:)

 foreach (var item in enterddetals.Attachments)
            {
                TicketAttachemnts attachemnt = new TicketAttachemnts();
                attachemnt.TicketNo = enterddetals.TicketNo;
                attachemnt.Name = Path.GetFileName(item.FileName);
                attachemnt.FileType = Path.GetExtension(item.FileName);
                using (var target = new MemoryStream())
                {   
                    item.CopyTo(target);
                    attachemnt.FileContent = target.ToArray();
                }
                string attachjson = JsonConvert.SerializeObject(attachemnt);
                response = await _azuredevopsmnger.CreateAttachement("DevOps/CreateAttachement",attachjson);
              

创建附件并将其链接到工作项

  ResultClass res = new ResultClass();
                var personalaccesstoken = "";
                string baseUrl = "https://.../_apis/wit/attachments?fileName={0}&api-version=5.0";
                string baseUrl2 = "https:/.../_apis/wit/workitems/{0}?api-version=5.0";
                string url= string.Format(baseUrl, attachments.Name);
                string url2= string.Format(baseUrl2, attachments.TicketNo);
                string msg1 = "Ticket created successfully!! Your Ticket ID is :{0}";
                string msg2 = "Ohh....Ticket creation  Failed !! Reson: {0}";
            var json = new StringContent(JsonConvert.SerializeObject(attachments.FileContent), Encoding.UTF8, "application/json-patch+json");
                try
                {
                   
                    using (HttpClient client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Accept.Add(
                            new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                            Convert.ToBase64String(
                                System.Text.ASCIIEncoding.ASCII.GetBytes(
                                    string.Format("{0}:{1}", "", personalaccesstoken))));

                        using (HttpResponseMessage response = client.PostAsync(url,json).Result)
                        {
                            response.EnsureSuccessStatusCode();
                            string responseBody = response.Content.ReadAsStringAsync().Result;
                            JObject data = JObject.Parse(responseBody);
                            string result = Convert.ToString(data["url"]);
                            List<Root> atc = new List<Root>();
                            Root att = new Root();
                            Attributes at = new Attributes();
                            Value v = new Value();
                            at.comment = "Spec for the work";
                            v.rel = "AttachedFile";
                            v.url = result;
                            v.attributes = at;
                            att.op = "add";
                            att.path = "/relations/-";
                            att.value = v;
                            atc.Add(att);
                            json = new StringContent(JsonConvert.SerializeObject(atc), Encoding.UTF8, "application/json-patch+json");
                           // return responseBody;
                        }
                        using (HttpResponseMessage response = client.PatchAsync(url2, json).Result)
                        {
                            response.EnsureSuccessStatusCode();
                            string responseBody = response.Content.ReadAsStringAsync().Result;
                            JObject data = JObject.Parse(responseBody);
                            int result = Convert.ToInt32(data["id"]);
                            res.IsSuccess = true;
                            res.ticketID = result;
                            res.message = string.Format(msg1, result);
                            return res;
                        }
[file stored in devops ][1]
[Error Msg when downloaded and opened it][1]

【问题讨论】:

  • 从文档中,端点attachements POST 等待application/octet-stream
  • 谢谢@Vernou,但我尝试了 jpj、png、xlxs 在从 UI 下载文件时仍然无法打开

标签: c# asp.net asp.net-web-api azure-devops azure-devops-rest-api


【解决方案1】:

问题来自您在创建附件时传递给client.PostAsync 方法的json 正文。

您应该将文件读取到字节并构建ByteArrayContent 而不是StringContent

我不知道上面的item 你的实例。但是当你创建一个附件时。首先,您需要将文件读入字节数组。例如:

var bitArr = File.ReadAllBytes(@"C:\Test\UploadTemp\pic.png");

然后转换为ByteArrayContent。例如。

var json = new ByteArrayContent(bitArr);
HttpResponseMessage response = client.PostAsync(url, json).Result;

请看下面的例子:

public string uploadAttachment() {
            
            #read the files as byteArray           
            var bitArr = File.ReadAllBytes(@"C:\Test\UploadTemp\pic.png");
                       
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                    Convert.ToBase64String(
                        System.Text.ASCIIEncoding.ASCII.GetBytes(
                            string.Format("{0}:{1}", "", personalaccesstoken))));
                
                var json = new ByteArrayContent(bitArr); ##convert to ByteArrayContent

                json.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                HttpResponseMessage response = client.PostAsync(url, json).Result;
                string responseBody = response.Content.ReadAsStringAsync().Result;
                JObject data = JObject.Parse(responseBody);
                string result = Convert.ToString(data["url"]);
                return result;

            }
}

我使用上面的代码来创建附件。从UI下载附件可以成功打开。

【讨论】:

  • 谢谢。一个小的澄清我的文件存储在[Display(Name = "Attachments")] public List&lt;IFormFile&gt; Attachments { get; set; }你能帮帮我吗?
  • @reckeyba IFormFile对象有哪些属性和方法。你能得到文件路径吗?
  • @Levi Lu-MSFT 谢谢。它工作了,我已经将var json = new StringContent(JsonConvert.SerializeObject(attachments.FileContent),Encoding.Default,"application/octet-stream"); 转换为此代码,并在 propperlyvar json = new ByteArrayContent(attachments.FileContent); json.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  • @reckeyba 很高兴知道它有效。你能accept above answer,因为它成功了吗?谢谢
猜你喜欢
  • 2020-09-13
  • 2020-05-25
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多