/// <summary> /// Create new attachment /// </summary> /// <param name="attachment">The attachment to be created</param> /// <param name="type">The type of the new attachment. Possible values are TeamPulse, FeedbackPortal. If not set TeamPulse is used</param> /// <returns>The created attachment</returns> public Attachment Create(int workItemId, AttachmentFileInfo file, string type = "TeamPulse") { string apiUrl = string.Format(ApiUrls.Attachments.Post, workItemId); string apiUrlQueryArgs = string.Format("{0}?type={1}", apiUrl, type); string postUrl = this.apiClient.CreateUrl(apiUrlQueryArgs); string responseContent = this.PostFile(postUrl, file); var attachment = SerializationHelper.DeserializeFromJson<Attachment>(responseContent); return attachment; }
private string PostFile(string postUrl, AttachmentFileInfo file) { string formDataBoundary = String.Format("----------{0}", Guid.NewGuid()); byte[] formData = GetMultipartFormData(formDataBoundary, file); HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest; request.Method = "POST"; request.ContentType = "multipart/form-data; boundary=" + formDataBoundary; ; request.ContentLength = formData.Length; request.Headers.Add("Authorization", "WRAP access_token=" + this.apiClient.GetAccessToken()); request.Accept = "application/json"; // Send the form data to the request. using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(formData, 0, formData.Length); requestStream.Close(); } StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()); string responseContent = sr.ReadToEnd(); return responseContent; }
private static byte[] GetMultipartFormData(string boundary, AttachmentFileInfo attFile) { Stream formDataStream = new System.IO.MemoryStream(); //formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n")); // Add just the first part of this param, since we will write the file data directly to the Stream StringBuilder header = new StringBuilder(); header.AppendLine("--" + boundary); header.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", "files", attFile.Name).AppendLine(); header.AppendFormat("Content-Type: {0}", attFile.ContentType).AppendLine(); header.AppendLine(); string headerString = header.ToString(); formDataStream.Write(Encoding.UTF8.GetBytes(headerString), 0, Encoding.UTF8.GetByteCount(headerString)); // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write(attFile.Data, 0, attFile.Data.Length); // Add the end of the request. Start with a newline string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return formData; }