0

I am working on ASP.Net project. I have to upload attachment to the defect in HP QC ALM 12.5x.

Authentication part is already done and successfully working.

On uploading defect to the attachment, receiving WebException was unhandled: The remote server returned an error: (415) Unsupported Media Type.

I have written the below code

string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HPALMUrl + "/rest/domains/" + HPALMDomain + "/projects/" + HPALMProject + "/attachments");
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("Accept-Language", "en-US");
request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)"; 
request.ContentType = "Content-Type: multipart/form-data; boundary=" + boundary;
request.AllowWriteStreamBuffering = false;
request.ContentLength = imageBytes.Length;
authRequest.KeepAlive = true;
request.CookieContainer = createSessionRequest.CookieContainer; //successfully authenticated cookie

string contentDisposition = "form-data; entity.type=\"{0}\"; entity.id=\"{1}\"; filename=\"{2}\"; Content-Type=\"{3}\"";
request.Headers.Add("Content-Disposition", string.Format(contentDisposition, "defect", "4", "Defect Attachment.png", "application/octet-stream")); //I am not clear with passing content disposition. Please let me know if this should be modified.

I am trying to upload Image file like below

string path = @"C:\TestAttachment.png";
byte[] imageBytes = System.IO.File.ReadAllBytes(path);
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
    using (MemoryStream memoryStream = new MemoryStream(imageBytes))
    {
        byte[] buffer = new byte[imageBytes.Length];
        int bytesRead = 0;
        while ((bytesRead = memoryStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            requestStream.Write(buffer, 0, bytesRead);
        }
    }
}

var response = (HttpWebResponse)request.GetResponse(); //Receiving Error here

string responseText = string.Empty;
if (response.StatusCode == HttpStatusCode.OK)
    responseText = "Update completed";
else
    responseText = "Error in update";

Please let me know what I am doing wrong.

I am also unsure of passing the content disposition mentioned in rest api.

Thanks in Advance!

Karthick Raju
  • 757
  • 8
  • 29
  • `Content-Disposition` is a *response* header. The *server* will set it in its response. Don't set it in the request at all – Panagiotis Kanavos Nov 15 '17 at 10:03
  • As for the error itself, attachments are *files* and yet your `Content-type` is `multipart/form-data`. You aren't posting a form. You are creating a new file. Perhaps you should check how HTTP in general and REST in particular work? – Panagiotis Kanavos Nov 15 '17 at 10:05
  • @PanagiotisKanavos But, in [API reference](https://admhelp.microfocus.com/alm/en/latest/api_refs/REST/webframe.htm#attachments.htm), Content-Disposition is mentioned in header part – Karthick Raju Nov 15 '17 at 10:06
  • Where? If you search for it you won't find that word – Panagiotis Kanavos Nov 15 '17 at 10:06
  • I found it. It's not a REST API at all, just form posting. – Panagiotis Kanavos Nov 15 '17 at 10:08
  • @PanagiotisKanavos, I am new to REST. Will the code work if I pass without content-disposition? If so, where do I have to pass Defect information. In API reference, I do not find this information. Sorry, if I am wrong. – Karthick Raju Nov 15 '17 at 10:09
  • Forget about REST. This is a plain-old Form POST. You don't pass `Content-Disposition` in the *header*. The form's *contents* consists of various parts, each one with its own headers. – Panagiotis Kanavos Nov 15 '17 at 10:11
  • @PanagiotisKanavos, OK, how do I have to pass defect information to upload attachment for Defect? – Karthick Raju Nov 15 '17 at 10:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/159044/discussion-between-karthick-raju-and-panagiotis-kanavos). – Karthick Raju Nov 15 '17 at 10:15

1 Answers1

1
def upload_result_file(self, defect_id, report_file):
    '''
        Function    :   upload_result_file
        Description :   Upload test result to ALM
    '''
    payload = open(report_file, 'rb')
    headers = {}
    headers['Content-Type'] = "application/octet-stream"
    headers['slug'] = "test-results" + report_file[report_file.rfind(".")+1: ]
    response = self.alm_session.post(ALM_URL + ALM_MIDPOINT + "/defects/" +
                                     str(defect_id) + "/attachments/",
                                     headers=headers, data=payload)
    if not (response.status_code == 200 or response.status_code == 201):
        print "Attachment step failed!", response.text, response.url, response.status_code
    return
Barney
  • 1,851
  • 2
  • 19
  • 36