一、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=""; 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 ((fileName) == false)
throw new Exception("发送文件不存在!");
FileInfo file = new FileInfo(fileName);
string boundary = "qianle";//分隔符
HttpWebRequest req = (url) as HttpWebRequest;
//构造请求体
byte[] itemBoundaryBytes = Encoding.("\r\n--" + boundary + "\r\n");
byte[] byteEnd = Encoding.("\r\n--" + boundary + "--\r\n"); //结束标识 --xxxx--
StringBuilder strContent = new StringBuilder();
strContent
.Append("Content-Disposition:form-data;name=\"filename\";filename=\"" + + "\"")
.AppendLine()
.Append("Content-Type:application/octet-stream")
.AppendLine()
.AppendLine(); //特别说明,Content-Disposition 前边不能添加换行符号
byte[] byteContent = Encoding.(());
byte[] byteFile = (fileName);
//执行发送
= "POST";
= $"multipart/form-data;charset=utf-8;boundary={boundary}";
= UserAgent;
= 20000;
var reqStrem = ();
(itemBoundaryBytes, 0, ); //文件开始
(byteContent, 0, );//文件信息
(byteFile, 0, );//文件内容
(byteEnd, 0, ); //文件结束
();
WebResponse resp = ();
StreamReader sr = new StreamReader(());
string result = ();
();
();
return result;
}
多文件上传参考:
c# WebApi POST请求同时包含数据及其文件_最数据的博客-****博客
三、C# 服务器端接受 form提交的文件:
C# HTML Form表单文件上传处理
更多:
C# HTML Form表单文件上传处理