使用 WebRequest 发送文件
以向微信接口上传媒体文件为例子,通过拼接 multipart/form-data 格式完成向请求附加文件。
public string UploadMedia(){
var accessToken = "";
var type = "image";
string filePath = "\path\to\file.png";
string fileName = "app.png";
var apiUrl = $"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={accessToken}&type={type}";
var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
var fileInfoPart = $"Content-Disposition: form-data; name=\"file\"; filename=\"{fileName}\"\r\nContent-Type: image/png";
var startBuffer = Encoding.UTF8.GetBytes($"--{boundary}\r\n{fileInfoPart}\r\n\r\n");
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var fileBuffer = new BinaryReader(fileStream).ReadBytes((int)fileStream.Length);
var endBoundaryBuffer = Encoding.UTF8.GetBytes($"\r\n--{boundary}--\r\n");
var request = WebRequest.Create(apiUrl);
request.Method = "POST";
request.Timeout = 100000;
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.ContentLength = startBuffer.Length + fileBuffer.Length + endBoundaryBuffer.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(startBuffer, 0, startBuffer.Length);
requestStream.Write(fileBuffer, 0, fileBuffer.Length);
requestStream.Write(endBoundaryBuffer, 0, endBoundaryBuffer.Length);
requestStream.Close();
var response = request.GetResponse();
using (var httpStreamReader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
var responseContent = httpStreamReader.ReadToEnd();
return Success(responseContent);
}
}