/// <summary>
/// 服务号:上传多媒体文件
/// </summary>
/// <param name="accesstoken">调用接口凭据</param>
/// <param name="type">图片(image)、语音(voice)、视频(video)和缩略图(thumb)</param>
/// <param name="filename">文件路径</param>
/// <param name="contenttype">文件Content-Type类型(例如:image/jpeg、audio/mpeg)</param>
/// <returns></returns>
public static string UploadFile_voicn(string accesstoken, string type, string filename, string contenttype)
{
/// <summary>
/// 根据完整文件路径获取FileStream
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
//文件
FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fileStream);
byte[] buffer = br.ReadBytes(Convert.ToInt32(fileStream.Length));
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//请求
WebRequest req = WebRequest.Create(@"#" + accesstoken + "&type=" + type);
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
//组织表单数据
StringBuilder sb = new StringBuilder();
sb.Append("--" + boundary+"\r\n");
sb.Append("Content-Disposition: form-data; name=\"media\"; filename=\"" + filename + "\"; filelength=\""+fileStream.Length+"\"");
sb.Append("\r\n");
sb.Append("Content-Type: "+contenttype);
sb.Append("\r\n\r\n");
string head = sb.ToString();
byte[] form_data = Encoding.UTF8.GetBytes(head);
//结尾
byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
//post总长度
long length = form_data.Length + fileStream.Length + foot_data.Length;
req.ContentLength = length;
Stream requestStream = req.GetRequestStream();
//这里要注意一下发送顺序,先发送form_data > buffer > foot_data
//发送表单参数
requestStream.Write(form_data, 0, form_data.Length);
//发送文件内容
requestStream.Write(buffer,0,buffer.Length);
//结尾
requestStream.Write(foot_data, 0, foot_data.Length);
requestStream.Close();
fileStream.Close();
fileStream.Dispose();
br.Close();
//br.Dispose();
//响应
WebResponse pos = req.GetResponse();
StreamReader sr = new StreamReader(pos.GetResponseStream(), Encoding.UTF8);
string html = sr.ReadToEnd().Trim();
sr.Close();
sr.Dispose();
if (pos != null)
{
pos.Close();
pos = null;
}
if (req != null)
{
req = null;
}
return html;
}
后端服务出异常,你这个代码就只能抓到Internal Server Error。用VS运行你的代码,会有出错提示。
哪大神这个要怎么搞?求教
@SummerTang: 先把真正的异常找出来才知道如何解决呢~
毫无疑问是抛异常了啦,自行调试不就知道问题出在什么地方了吗!
服务器异常,想办法调试吧。