/// <summary>
///
/// </summary>
/// <param name="url">API URL</param>
/// <param name="token">API token</param>
/// <param name="parameters">API参数(除文件类型外)</param>
/// <param name="fileContent">文件参数(二进制文件流)</param>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public string Post_formdata(string url, string token, Dictionary<string, string> parameters, byte[] fileContent, string fileName)
{
string result = "";
string strBoundary = "--" + DateTime.Now.Ticks.ToString("x");//程序生成
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
if (!string.IsNullOrEmpty(token))
{
WebHeaderCollection coll = new WebHeaderCollection();
coll.Add("token", token);
request.Headers = coll;
}
request.ContentType = "multipart/form-data;charset=UTF-8; boundary=" + strBoundary;
// 设置请求参数
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> kvp in parameters)
{
sb.AppendFormat("--" + strBoundary + "\r\n");
sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n", kvp.Key);
sb.AppendFormat("\r\n{0}\r\n", kvp.Value);
}
// 上传文件
sb.AppendFormat("--" + strBoundary + "\r\n");
sb.AppendFormat("Content-Disposition: form-data; name=\"uploadFile\"; filename=\"{0}\"\r\n", fileName); //uploadFile为参数名
//sb.AppendFormat("Content-Type: image/png\r\n");
sb.AppendFormat("Content-Type: octet-stream\r\n");
sb.AppendFormat("\r\n");
byte[] paramBytes= Encoding.UTF8.GetBytes(sb.ToString());
var footerBytes = Encoding.UTF8.GetBytes("\r\n--" + strBoundary + "--\r\n");
byte[] fileBytes = fileContent;
request.ContentLength += fileBytes.Length + paramBytes.Length + footerBytes.Length + 1;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(paramBytes, 0, paramBytes.Length);
requestStream.Write(fileBytes, 0, fileBytes.Length);
requestStream.Write(footerBytes, 0, footerBytes.Length);
}
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
resp = (HttpWebResponse)ex.Response;
}
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
resp.Close();
request.Abort();
return result;
}