一、Http Post请求附带文件的请求报文格式
boundary=xxxx 文件分隔符,可以自己定义
------xxxxx 文件分割开始
------xxxxx-- 文件分割结束。
Header内容:
Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
Content-Length: 220
content内容:
---------------------------acebdf13572468
Content-Disposition: form-data; name="media";filename="wework.txt"; filelength=6
Content-Type: application/octet-stream
mytext (文件的二进制字符串)
---------------------------acebdf13572468--
二、C# Post 发送文件代码示例
/// <summary>
/// Post 请求发送文件
/// </summary>
/// <param name="url"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static string PostFile(string url, string fileName)
{
//验证文件是否存在
if (File.Exists(fileName) == false)
throw new Exception("发送文件不存在!");
FileInfo file = new FileInfo(fileName);
string boundary = "qianle";//分隔符
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
//构造请求体
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] byteEnd = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //结束标识 --xxxx--
StringBuilder strContent = new StringBuilder();
strContent
.Append("Content-Disposition:form-data;name=\"filename\";filename=\"" + file.Name + "\"")
.AppendLine()
.Append("Content-Type:application/octet-stream")
.AppendLine()
.AppendLine(); //特别说明,Content-Disposition 前边不能添加换行符号
byte[] byteContent = Encoding.UTF8.GetBytes(strContent.ToString());
byte[] byteFile = File.ReadAllBytes(fileName);
//执行发送
req.Method = "POST";
req.ContentType = $"multipart/form-data;charset=utf-8;boundary={boundary}";
req.UserAgent = UserAgent;
req.ContinueTimeout = 20000;
var reqStrem = req.GetRequestStream();
reqStrem.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); //文件开始
reqStrem.Write(byteContent, 0, byteContent.Length);//文件信息
reqStrem.Write(byteFile, 0, byteFile.Length);//文件内容
reqStrem.Write(byteEnd, 0, byteEnd.Length); //文件结束
reqStrem.Close();
WebResponse resp = req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
resp.Close();
return result;
}
多文件上传参考:
c# WebApi POST请求同时包含数据及其文件_最数据的博客-CSDN博客
三、C# 服务器端接受 form提交的文件:
更多: