Stab in the dark - 边界字符串需要有一个前导--
,并且消息的最后一行必须有格式:--boundarystring--
,否则消息无效。Wikipedia 上的MIME 条目包含一个很好的示例,说明消息的外观。将请求转储到文件并确保它是有效的多部分消息是一个好的开始。
编辑
您应该真正使用System.Net.WebClient框架,而不是您正在使用的方法。它封装了所有这些功能。
通过改变你的哑剧身体构造,我成功地从脚本上传。请注意,我Content-Type
从参数中删除了它,因为它不需要,另外我确保正确形成了边界字符串,即传入的字符串boundaryString
与请求标头中使用的字符串一样,没有前导--
我让函数执行双重任务——它仅在 Stream 为null
.
public static long sendMultiPartReq(Stream req, string boundaryString, object[] files, object[] parameters)
{
String CRLF = "\r\n";
byte[] b;
long contentLength = 0;
foreach (string[] file in files)
{
b = Encoding.UTF8.GetBytes(
CRLF + "--" + boundaryString + CRLF +
String.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + CRLF,
file[0], Path.GetFileName(file[1])) +
"Content-Type: image/png" + CRLF + CRLF);
contentLength += b.LongLength;
if (req != null) req.Write(b, 0, b.Length);
if (File.Exists(file[1]))
{
b = File.ReadAllBytes(file[1]);
contentLength += b.LongLength;
if (req != null) req.Write(b, 0, b.Length);
}
b = Encoding.UTF8.GetBytes(CRLF);
contentLength += b.LongLength;
if (req != null) req.Write(b, 0, b.Length);
}
foreach (string[] parameter in parameters)
{
b = Encoding.UTF8.GetBytes(
"--" + boundaryString + CRLF +
String.Format("Content-Disposition: form-data; name=\"{0}\"" + CRLF, parameter[0]) +
CRLF + parameter[1] + CRLF);
contentLength += b.LongLength;
if (req != null) req.Write(b, 0, b.Length);
}
b = Encoding.UTF8.GetBytes("--" + boundaryString + "--" + CRLF);
contentLength += b.LongLength;
if (req != null) req.Write(b, 0, b.Length);
return contentLength;
}