我很难找出导致输出流中出现奇怪字符的原因...完整代码 @pastebin
Fiddler输出
在我的边界之前注意“s
”,“X
”,“�
”?
s---------------634227387532666996
Content-Disposition: form-data; name='key'
c06f4d0cdf6f2cc652635a08be34973d
X---------------634227387532666996
Content-Disposition: form-data; name='type'
file
�---------------634227387532666996
Content-Disposition: form-data; name='image'; filename='application_osx_split.png'
Content-Type=image/png
�PNG
我的代码
var bound = "-------------" + DateTime.Now.Ticks.ToString();
var tmplField = "--" + bound + "\r\nContent-Disposition: form-data; name='{0}'\r\n\r\n{1}\r\n";
var tmplFile = "--" + bound + "\r\nContent-Disposition: form-data; name='{0}'; filename='{1}'\r\nContent-Type={2}\r\n\r\n";
....
using (var reqStream = req.GetRequestStream())
{
var reqWriter = new BinaryWriter(reqStream);
reqWriter.Write(string.Format(tmplField, "key", "c06f4d0cdf6f2cc652635a08be34973d"));
reqWriter.Write(string.Format(tmplField, "type", "file"));
reqWriter.Write(string.Format(tmplFile, "image", Path.GetFileName(filepath), "image/" + Path.GetExtension(filepath).Substring(1)));
reqWriter.Write(File.ReadAllBytes(filepath));
reqWriter.Write("\r\n--" + bound + "--");
reqWriter.Flush();
}
更新
我注意到如果我做了类似下面的事情,使用Stream& amp;二元作家,我可以避免这个问题。为什么会这样?
var reqWriter = new StreamWriter(reqStream);
reqWriter.Write(string.Format(tmplField, "key", "c06f4d0cdf6f2cc652635a08be34973d"));
reqWriter.Write(string.Format(tmplField, "type", "file"));
reqWriter.Write(string.Format(tmplFile, "image", Path.GetFileName(filepath), "image/" + Path.GetExtension(filepath).Substring(1)));
reqWriter.Flush();
var binWriter = new BinaryWriter(reqStream);
binWriter.Write(File.ReadAllBytes(filepath));
binWriter.Write("\r\n--" + bound + "--");
binWriter.Flush();
答案 0 :(得分:5)
BinaryWriter为字符串添加长度前缀。
改为使用StreamWriter。