[Note this article uses the v5.0 REST API, please refer to KB604 for the newer v6.0 REST API]
In this example, we're using the following API:
POST: projects/{project_id}/documents/file?filename={filename}&tags={tags}&folder_id={folder_id}&document_type_id={document_type_id}&artifact_type_id={artifact_type_id}&artifact_id={artifact_id}
Description
Adds a new document (file) into the system and associates it with the provided artifact (optional) and project folder/type (optional)
The file must be converted into an array of bytes. Include this and nothing else into the body of the request. The array will take the form of: [number1, number2, number3, and so on], where each number is a value between 0 and 255.
How to Execute
To access this REST web service, you need to use the following URL (make sure to replace any parameters (eg {project_id}) with the relevant value (eg 1).
Sample Code
/// <summary>
/// Uploads the file
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
//Create the full URL
string url = this.txtUrl.Text.Trim() + "/Services/v5_0/RestService.svc/projects/{project_id}/documents/file?filename={filename}";
string projectId = this.txtProject.Text.Trim();
string filename = Path.GetFileName(this.txtFilename.Text);
url = url.Replace("{project_id}", projectId);
url = url.Replace("{filename}", filename);
//Create the HTTP Post
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = "POST";
//Add the authentication
string base64Credentials = GetEncodedCredentials();
request.Headers.Add("Authorization", "Basic " + base64Credentials);
//Read the file and turn into JSON byte array
byte[] contents = File.ReadAllBytes(this.txtFilename.Text);
string json = "[";
bool first = true;
foreach (byte item in contents)
{
if (!first)
{
json += ",";
}
else
{
first = false;
}
json += item.ToString();
}
json += "]";
//Add the filename body
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
//writer.Write("[0,0,0,0,0,0,0,0,0,0,0,0,0]");
writer.Write(json);
}
//Fire the query and get the response
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
MessageBox.Show("Done!");
}
/// <summary>
/// Gets the base64-encoded login/password
/// </summary>
/// <returns></returns>
private string GetEncodedCredentials()
{
string mergedCredentials = string.Format("{0}:{1}", this.txtLogin.Text.Trim(), this.txtPassword.Text.Trim());
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
return Convert.ToBase64String(byteCredentials);
}