因为除了上传文件外,还要传入多个参数,但是参数不知道写在哪里?要写&符号进行连接参数吗?
下面是我在网上找的代码:
public bool LinkWebUpload(string URL, string filePath, string filename) { bool flag = false; //上传是否成功的标志 int position = filePath.IndexOf(originFileName, 0); //查找上传文件夹的起始目录名的位置,返回的是第一个匹配项的位置 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); //请求头部信息 StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(strBoundary); sb.Append("\r\n"); sb.Append("Content-Disposition:form-data;name=\""); sb.Append("file"); sb.Append("\";filename=\""); sb.Append(filename); sb.Append("\";"); sb.Append("\r\n"); sb.Append("Content-type:"); sb.Append("application/octet-stream"); sb.Append("\r\n"); sb.Append("\r\n"); string strPostHeader = sb.ToString(); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(URL)); //根据URL创建HttpWebRequestion对象 httpReq.Method = "POST"; //采用post方法上传 httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存 httpReq.Timeout = 300000; //设置获得响应的超时时间(300秒) httpReq.ContentType = "multipart/form-data;boundary=" + strBoundary; long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length; long fileLength = fs.Length; httpReq.ContentLength = length; try { int bufferLength = 4096; //每次上传4K byte[] buffer = new byte[bufferLength]; long offset = 0; //已上传的字节数 DateTime startTime = DateTime.Now; int size = r.Read(buffer, 0, bufferLength); Stream postStream = httpReq.GetRequestStream(); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); while (size > 0) { postStream.Write(buffer, 0, size); offset += size; size = r.Read(buffer, 0, bufferLength); } postStream.Write(boundaryBytes, 0, boundaryBytes.Length); //添加尾部时间戳 postStream.Close(); WebResponse response = httpReq.GetResponse(); //获取服务器的响应 Stream res = response.GetResponseStream(); StreamReader sr = new StreamReader(res); //读取服务器返回的数据 string strRes = sr.ReadLine(); res.Close(); sr.Close(); if (strRes == "Success") { flag = true; } else if (strRes == "ERROR") { flag = false; } } catch { flag = false; } finally { fs.Close(); r.Close(); } return flag; }
有人写过 http://www.cnblogs.com/GodX/archive/2016/06/21/5604944.html
一切可书写的地方皆可为参数;
你要看服务器参数的定义,是URL的还是Head的还是Body的。有的Http框架直接整合了URL和Body的。比如上文中相对一般请求多了几个Head参数。
可能是你上传文件做了限制吧,需要登录用户,所以你要先模拟登录一下?