REST API - Using the Content-Type: Multipart Method

Updated by Stefenie Stockbridge

You can use the Multipart method with the following requests:

To add data using the Multipart method, you must use boundary parameters for the data. For more information on using MultipartContent, see http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html.

Example in C#

{
//Call REST API
var fetchRequest = (HttpWebRequest)WebRequest.Create(string.Concat(BaseURI, "/", APICall));
fetchRequest.Headers.Add("Authorization", “BlueprintToken” + “ “ + authenticationToken);

fetchRequest.Accept = "application/xml";
fetchRequest.Method = "POST";
fetchRequest.KeepAlive = true;

fetchRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

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

fetchRequest.ContentType = "multipart/form-data; boundary=" + boundary;
using (Stream rs = fetchRequest.GetRequestStream())
{
//Add starting boundary
rs.Write(boundarybytes, 0, boundarybytes.Length);

//Add Content headers (content disposition header)
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);

//Add file
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
}

//Add last boundary
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
}
//Send request
var webResponse = fetchRequest.GetResponse() as HttpWebResponse;

}


How did we do?