I am trying to upload a media item(image) using a specified template so I can utilize some extra field properties of the item. However, the image gets uploaded and still continues to use the default image template. Fiddler doesn't show any errors either.
What am I doing wrong? Any suggestions? Here is the code snip:
public void PostPicture(string itemName, Guid parentId, string databaseName, Stream fileStream, string fileExtension)
{
string url = String.Format("{0}/-/item/v1?", this.Host.TrimEnd('/'));
string imageTemplate = "{0E49E3DF-69C2-4F4B-9513-F078EA0013B2}";
url += String.Format("name={0}&template={1}&sc_itemid={2}&sc_database={3}&payload=content&language=en"
, HttpUtility.UrlEncode(itemName)
, HttpUtility.UrlEncode(imageTemplate)
, HttpUtility.UrlEncode(parentId.ToString())
, HttpUtility.UrlEncode(databaseName));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Add("X-Scitemwebapi-Username", this.Username);
request.Headers.Add("X-Scitemwebapi-Password", this.Password);
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string boundary = "---------------------------" + DateTime.Now.ToString("yyyyMMddHHmmssfff", System.Globalization.CultureInfo.InvariantCulture);
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
request.ContentType = "multipart/form-data; boundary=" + boundary;
using (Stream stream = request.GetRequestStream())
{
stream.Write(boundaryBytes, 0, boundaryBytes.Length);
string header = "Content-Disposition: form-data; name=\"file\"; filename=\"" + itemName + fileExtension + "\"\r\nContent-Type: multipart/form-data\r\n\r\n";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(header);
stream.Write(bytes, 0, bytes.Length);
byte[] buffer = new byte[32768];
int bytesRead;
if (stream != null)
{
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
byte[] end = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
stream.Write(end, 0, end.Length);
stream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
}
}
One possible approach is to change the "sharedTemplate" and/or "versionedTemplate" settings in the "mediaTypes" node of the Web.config file. You will find entries for various types of media files and images (ex: png, bmp, jpg) and you should change the default template for all necessary file types.
Here is a post I wrote on the topic that will show you an example of how to make the changes in a custom config file instead of directly in the Web.config file. https://sitecorecontextitem.wordpress.com/2012/12/12/custom-image-templates-in-sitecore/