Hello,
I'm trying to upload videos in Youtube through HttpWebRequest. Everything seems to be fine when uploading following the example given in API documentation.
I see that request is being formed correctly, with content and token sent but I receive "Incomplete multipart body" as response.
Thanks Blerim
public bool YouTubeUpload()
{
string newLine = "\r\n";
//token and url are retrieved from YouTube at runtime.
string token = string.Empty;
string url = string.Empty;
// construct the command url
url = url + "?nexturl=http://www.mywebsite.com/";
// get a unique string to use for the data boundary
string boundary = Guid.NewGuid().ToString().Replace("-", string.Empty);
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
// get info about the file and open it for reading
Stream fs = hpf.InputStream;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
webRequest.Method = "POST";
webRequest.KeepAlive = true;
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream);
//token
writer.Write("--" + boundary + newLine);
writer.Write("Content-Disposition: form-data; name=\"{0}\"{1}{2}", "token", newLine, newLine);
writer.Write(token);
writer.Write(newLine);
//Video
writer.Write("--" + boundary + newLine);
writer.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", "File1", hpf.FileName, newLine);
writer.Write("Content-Type: {0}" + newLine + newLine, hpf.ContentType);
writer.Flush();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes(string.Format("--{0}--{1}", boundary, newLine));
webRequest.ContentLength = memoryStream.Length + fs.Length + boundarybytes.Length;
Stream webStream = webRequest.GetRequestStream();
// write the form data to the web stream
memoryStream.Position = 0;
byte[] tempBuffer = new byte[memoryStream.Length];
memoryStream.Read(tempBuffer, 0, tempBuffer.Length);
memoryStream.Close();
webStream.Write(tempBuffer, 0, tempBuffer.Length);
// write the file to the stream
int size;
byte[] buf = new byte[1024 * 10];
do
{
size = fs.Read(buf, 0, buf.Length);
if (size > 0)
webStream.Write(buf, 0, size);
} while (size > 0);
// write the trailer to the stream
webStream.Write(boundarybytes, 0, boundarybytes.Length);
webStream.Close();
fs.Close();
//fails here. Error - Incomplete multipart body.
WebResponse webResponse = webRequest.GetResponse();
}
return true;
}