using System.IO;
using System.Net;
using Newtonsoft.Json;
//address是要上传到的服务器地址路径,fileNamePath是文件的本地地址路径
public static string Upload_Request(string address,string fileNamePath)
{
//打开要上传的文件流
FileStream fs=new FileStream(fileNamePath,FileMode.Open,FileAccess.Read);
//时间戳
string strBoundary="--------"+DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytesEnd=Encoding.ASCII.GetBytes("\r\n--"+strBoundary+"--\r\n");
//请求头部信息
byte[] postHeaderBytes=Encoding.UTF8.GetBytes("--"+strBoundary+"\r\nContent-Disposition:form-data;name=\"file\";filename=\""+Path.GetFileName(fileNamePath)+"\"\r\nContent-Type: application/octet-stream\r\n\r\n");
//根据uri创建HttpWebRequest对象
HttpWebRequest httpReq=(HttpWebRequest)WebRequest.Create(new Uri(address));
httpReq.Method="POST";
//对发送的数据不使用缓存(重要)
httpReq.AllowWriteStreamBuffering=false;
//设置获得响应的超时时间(300秒)
httpReq.Timeout=300000;
httpReq.ContentType="multipart/form-data;boundary="+strBoundary;
//计算上传信息的大小
long length=fs.Length+postHeaderBytes.Length+boundaryBytesEnd.Length;
long fileLength=fs.Length;
httpReq.ContentLength=length;
try
{
//每次上传32K
int bufferLength=32768;
byte[] buffer=new byte[bufferLength];
//将文件流读入buffer,准备上传
int size = fs.Read(buffer,0,bufferLength);
Stream postStream=httpReq.GetRequestStream();
//发送请求头部消息
postStream.Write(postHeaderBytes,0,postHeaderBytes.Length);
while(size>0)
{
//上传文件数据信息
postStream.Write(buffer,0,size);
size=fs.Read(buffer,0,bufferLength);
}
//发送尾部时间戳
postStream.Write(boundaryBytesEnd,0,boundaryBytesEnd.Length);
postStream.Close();
//获取服务器端响应
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
StreamReader sr= new StreamReader(s);
//读取服务器端返回的消息
String sReturnString = sr.ReadLine();
//解析返回的Json数据(UpLoadText是对应的实体类)
List
ult=JsonConvert.DeserializeObject
>(sReturnString);
string ulti = ult[0].file.ToString();
sr.Close();
s.Close();
webRespon.Close();
return ulti;
}
catch(Exception e)
{
return "error";
}
}