public static string UploadFile(string uploadUrl, string FilePath, Dictionary<string, string> dic, string token = "")
{
try
{
string postData = "";
int a = 0;
foreach (KeyValuePair<string, string> para in dic)
{
if (a != 0)
{
postData += "&" + para.Key + "=" + para.Value;
}
else
{
postData += para.Key + "=" + para.Value;
}
a++;
}
var postUrl = string.Format("{0}?{1}", uploadUrl, postData);//拼接url
request = WebRequest.Create(postUrl) as HttpWebRequest;
request.AllowAutoRedirect = false;
request.Method = "POST";
request.Headers.Add(string.Format("X-AUTH-TOKEN:{0}", token));
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
int pos = FilePath.LastIndexOf("\\");
string fileName = FilePath.Substring(pos + 1);
//请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, 0, bArr.Length);
fs.Close();
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bArr, 0, bArr.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
string content = sr.ReadToEnd();
LogHelper.WriteLog("上传文件成功:文件名" + fileName);
return content;
}
catch (Exception ex)
{
LogHelper.WriteLog("上传文件失败:" + ex.Message);
return string.Empty;
}
finally
{
request.Abort();
}
}