API Sample (C#) of how to Upload Attachments to the Help Center (Guide)
When doing a migration of Help Center articles, I ran into some trouble using the API to upload attachments to articles. This is a sample of how I was able to achieve this task.
private void UploadHelpAttachment(string fileName, string filePath)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://{subdomain}.zendesk.com/api/v2/help_center/articles/{articleid}/attachments.json?inline=true");
request.Method = "POST";
request.Accept = "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml";
request.Timeout = 100000000;
request.Headers.Add("Authorization", "Basic " + token);
using (var dataStream = request.GetRequestStream())
{
var data = GetFromData(fileName, filePath, request);
dataStream.Write(data, 0, data.Length);
}
var res = request.GetResponse();
var response = res as HttpWebResponse;
string responseFromServer = string.Empty;
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
responseFromServer = reader.ReadToEnd();
}
}
Response.Clear();
Response.ContentType = "application/json";
Response.Write(responseFromServer);
Response.End();
}
private byte[] GetFromData(string fileName, string filePath, HttpWebRequest request)
{
var attachment = System.IO.File.ReadAllBytes(filePath);
string boundaryString = new Guid.NewGuid().ToString();
MemoryStream postDataStream = new MemoryStream();
StreamWriter postDataWriter = new StreamWriter(postDataStream);
request.ContentType = "multipart/form-data; boundary=" + boundaryString;
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Flush();
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", "file", fileName, MimeMapping.GetMimeMapping(fileName));
postDataWriter.Flush();
postDataStream.Write(attachment, 0, attachment.Length);
postDataWriter.Write("\r\n--" + boundaryString + "--\r\n");
postDataWriter.Flush();
return postDataStream.ToArray();
}
-
Thanks for sharing this, Andrew!
I know it's already helped at least one person!
-
Hi Andrew,
This looks great. Question. Do you have any idea as to how to retrieve the user id and store it in a variable?
I've tried writing up an HTTP AJAX Request. It shows the users array within the console, but the variable comes up as undefined :(
Thank you!
Please sign in to leave a comment.
2 Comments