主体
Dictionary<string, object> postData = new Dictionary<string, object>();
string fileFullPath = this.imgFullPath;
if (!File.Exists(fileFullPath))
{
Message(Error, "file not exist: " + fileFullPath);
goto EndGetPost;
}
// 先定义一个byte数组
// 将指定的文件数据读取到 数组中
byte[] bFile = null;
// path是文件的路径
using (FileStream fs = new FileStream(fileFullPath, FileMode.Open))
{
// 定义这个byte[]数组的长度 为文件的length
bFile = new byte[fs.Length];
// 把fs文件读入到arrFile数组中,0是指偏移量,从0开始读,arrFile.length是指需要读的长度,也就是整个文件的长度
fs.Read(bFile, 0, bFile.Length);
}
postData.Add("file", new FileParameter(bFile, fileFullPath, "image/jpg"));
//--------------------------------------
// Create request and receive response
string postURL = this.url;
string userAgent = "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);
// Process response
StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
fullResponse = responseReader.ReadToEnd();
responseReader.Close();
webResponse.Close();
类
/// <summary>
/// 表单数据项.
/// </summary>
public static class FormUpload
{
private static readonly Encoding ENCODING = Encoding.UTF8;
/// <summary>
/// MultipartFormDataPost.
/// </summary>
/// <param name="postUrl">.</param>
/// <param name="userAgent">string.</param>
/// <param name="postParameters">send.</param>
/// <returns>HttpWebResponse.</returns>
public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
{
string formDataBoundary = string.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
return PostForm(postUrl, userAgent, contentType, formData);
}
/// <summary>
/// send to api.
/// </summary>
/// <param name="postUrl">url.</param>
/// <param name="userAgent">string agent.</param>
/// <param name="contentType">send type.</param>
/// <param name="formData">type.</param>
/// <returns>HttpWebResponse.</returns>
private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
{
// use https or http
// HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
HttpWebRequest request = null;
if (postUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
Message(Warning, "use https:-------");
request = WebRequest.Create(postUrl) as HttpWebRequest;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request.ProtocolVersion = HttpVersion.Version11;
// 这里设置了协议类型。
// SecurityProtocolType.Tls1.2;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
request.KeepAlive = false;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.Expect100Continue = false;
}
else
{
Message(Warning, "use http default");
request = (HttpWebRequest)WebRequest.Create(postUrl);
}
// start -------
if (request == null)
{
throw new NullReferenceException("request is not a http request");
}
// Set up the request properties.
request.Method = "POST";
request.ContentType = contentType;
request.UserAgent = userAgent;
request.CookieContainer = new CookieContainer();
request.ContentLength = formData.Length;
request.Accept = "application/json";
// You could add authentication here as well if needed:
// request.PreAuthenticate = true;
// request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
// request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));
// Send the form data to the request.
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
return request.GetResponse() as HttpWebResponse;
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
{
formDataStream.Write(ENCODING.GetBytes("\r\n"), 0, ENCODING.GetByteCount("\r\n"));
}
needsCLRF = true;
if (param.Value is FileParameter)
{
FileParameter fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format(
"--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
formDataStream.Write(ENCODING.GetBytes(header), 0, ENCODING.GetByteCount(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
}
else
{
string postData = string.Format(
"--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(ENCODING.GetBytes(postData), 0, ENCODING.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(ENCODING.GetBytes(footer), 0, ENCODING.GetByteCount(footer));
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
/// <summary>
/// CheckValidationResult.
/// </summary>
/// <param name="sender">sender.</param>
/// <param name="certificate">certificate.</param>
/// <param name="chain">chain.</param>
/// <param name="errors">errors.</param>
/// <returns>true.</returns>
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// 总是接受
return true;
}
}
/// <summary>
/// FileParameter.
/// </summary>
public class FileParameter
{
/// <summary>
/// Initializes a new instance of the <see cref="FileParameter"/> class.
/// FileParameter.
/// </summary>
/// <param name="file">file.</param>
/// <param name="filename">filename.</param>
/// <param name="contenttype">contenttype.</param>
public FileParameter(byte[] file, string filename, string contenttype)
{
this.File = file;
this.FileName = filename;
this.ContentType = contenttype;
}
/// <summary>
/// Gets or sets File.
/// </summary>
public byte[] File { get; set; }
/// <summary>
/// Gets or sets FileName.
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Gets or sets ContentType.
/// </summary>
public string ContentType { get; set; }
}