我正在尝试通过HttpWebRequest在Youtube上传视频。按照API文档中给出的示例上传时,一切似乎都很好。 我看到请求正在形成,内容和令牌已发送,但我收到“不完整的多部分正文”作为回复。
谢谢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;
}