利用公众平台模拟上传图片,老是返回上传文件失败,急...
大家帮帮忙:
最近遇到一个问题一直解决不了,我模拟登录获取cookie后想上传图片,但是老上上传不上去,服务器返回失败.
返回了一段javascript
<script>
document.domain = location.hostname.match(/[^\.]*?\.[^\.]*?$/);
var
url = window.location.href,
type = url.match(/[\?&]type=([^&]*)/),
formId = url.match(/[\?&]formId=([^&]*)/);
type = type[1] || 0;
formId = formId[1];
top.W.upload.err("上传文件失败", type, formId);
</script>
谁能告诉我是那方面出问题了,还是说服务器判断出来了吗?没有一点头绪.
[解决办法]
public static string UploadFile(string fileSrc)
{
CookieContainer cookie = LoginInfo.LoginCookie; //模拟登录获得的cookie
string token = LoginInfo.Token; //模拟登录获得的Token
HttpWebRequest req;
string url = @"https://mp.weixin.qq.com/cgi-bin/uploadmaterial?cgi=uploadmaterial&type=2&token={0}&t=iframe-uploadfile&lang=zh_CN&formId=file_from_1341151893625";
url = string.Format(url, token);
req = (HttpWebRequest)WebRequest.Create(url);
string filePath = fileSrc; //要上传文件本地路径,如D:\\ms.jpg
byte[] filebytes = File.ReadAllBytes(filePath);
req.Method = "POST";
req.Accept = "*/*";
req.AllowAutoRedirect = true;
req.Credentials = System.Net.CredentialCache.DefaultCredentials;
req.Referer = string.Format("https://mp.weixin.qq.com/cgi-bin/indexpage?token={0}&t=wxm-upload&lang=zh_CN&type=0&fromId=file_from_1341151893625", token);
string boundary = "----" + DateTime.Now.Ticks.ToString("x");
req.Host = "mp.weixin.qq.com";
req.ContentType = "multipart/form-data; boundary=" + boundary;
req.KeepAlive = true;
req.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
if (cookie != null)
{
req.CookieContainer = new CookieContainer();
req.CookieContainer = cookie;
}
byte[] boundarybyte = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] fileHeader = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name="uploadfile"; filename="2.jpg"\r\nContent-Type: image/jpeg\r\n\r\n"); //2.jpg为上传后保存的文件名,通过修改image/jpeg可以上传音频
byte[] formData = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name="formId"\r\n\r\n");
byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");
Stream memStream = new MemoryStream();
memStream.Write(fileHeader, 0, fileHeader.Length);
memStream.Write(boundarybyte, 0, boundarybyte.Length);
memStream.Write(fileHeader, 0, fileHeader.Length);
memStream.Write(filebytes, 0, filebytes.Length);
memStream.Write(boundarybyte, 0, boundarybyte.Length);
memStream.Write(formData, 0, formData.Length);
memStream.Write(trailer, 0, trailer.Length);
req.ContentLength = memStream.Length;
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
Stream reqStream = req.GetRequestStream();
reqStream.Write(tempBuffer, 0, tempBuffer.Length);
reqStream.Close();
HttpWebResponse resp;
resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
string html = sr.ReadToEnd().Trim();//输出结果
resp.Close();
return html;
}