Hi Peter, thanks for the reply.
below is my code. The file parameter is the last one being attached to the form. No matter what I try I keep getting Bad Request 400. The CanvasFileUploadRequest object contains the parameters returned from the first step. I can see everything is being added successfully.
public string UploadFile(CanvasFileUploadRequest response, byte[] fileByteArray, string fileName, string contentType)
{
var values = new NameValueCollection();
var files = new Dictionary<string, byte[]>();
values.Add("key", response.UploadParams["key"]);
foreach (var key in response.UploadParams.Keys)
{
if (key == "key") continue;
values.Add(key, response.UploadParams[key]);
}
files.Add("profilePicture", fileByteArray);
sendHttpRequest(response.UploadUrl, values, files);
return string.Empty;
}
//method that constructs the multi part form
private static string sendHttpRequest(string url, NameValueCollection values, Dictionary<string, byte[]> files)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
// The first boundary
byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
// The last boundary
byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
// The first time it itereates, we need to make sure it doesn't put too many new paragraphs down or it completely messes up poor webbrick
byte[] boundaryBytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
// Create the request and set parameters
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
//request.Credentials = CredentialCache.DefaultCredentials;
// Get request stream
Stream requestStream = request.GetRequestStream();
foreach (string key in values.Keys)
{
// Write item to stream
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}", key, values[key]));
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Write(formItemBytes, 0, formItemBytes.Length);
}
if (files != null)
{
foreach (string key in files.Keys)
{
//byte[] buffer = new byte[2048];
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n", key, files[key]));
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Write(formItemBytes, 0, formItemBytes.Length);
var file = files[key];
requestStream.Write(file, 0, file.Length);
}
}
// Write trailer and close stream
requestStream.Write(trailer, 0, trailer.Length);
requestStream.Close();
using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()))
{
return reader.ReadToEnd();
};
}