声明webclient对象,添加header。上传文件的content-type需指定multipart/form-data,multipart为多文件,boundary为分割符可以为任意字符串 WebClient webClient = new WebClient(); webClient.Headers.Add("content-type
声明webclient对象,添加header。上传文件的content-type需指定multipart/form-data,multipart为多文件,boundary为分割符可以为任意字符串
WebClient webClient = new WebClient();
webClient.Headers.Add("content-type", "multipart/form-data; boundary=" + boundary);
webClient.Headers.Add("Accept", "*/*");
webClient.Headers.Add("User-Agent", "PostmanRuntime/7.4.0");
添加上传数据,每个boundary前需要加上--,最后一个boundary前后都需要加入--。
try
{
string ContentType = "Content-Disposition: form-data; name=\"FileName\"; filename=\"{0}\"\r\nContent-Type: application/xml\r\n\r\n";
byte[] headByte = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); //头数据
byte[] typeByte = Encoding.UTF8.GetBytes(string.Format(ContentType, fileName)); // ContentType 数据
byte[] endBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //尾数据
FileStream fs = new FileStream(filePath, FileMode.Open,
FileAccess.Read, FileShare.Read);
byte[] fileBytes = new byte[fs.Length]; // 文件的二进制数据
fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
// 合成后的数组
byte[] fieldData = new byte[fileBytes.Length + headByte.Length + endBytes.Length + typeByte.Length];
headByte.CopyTo(fieldData, 0);
typeByte.CopyTo(fieldData, headByte.Length);
fileBytes.CopyTo(fieldData, headByte.Length + typeByte.Length);
endBytes.CopyTo(fieldData, headByte.Length + fileBytes.Length + typeByte.Length);
}
组装好的数据最终调用UploadData上传
responseBytes = webClient.UploadData(uploadUrl, fieldData);