[基本上与此人相同,不幸的是线程在被回答之前就死了。] WebClient's UploadFile and UploadData not sending same headers (with multipart/form-data)
我可以使用WebClients UploadFile上载文件,但是无法使用UploadData上载转换为字节数组的相同文件。
提琴手的不同之处: 在UploadData上:Content-Length:13264
Content-Type:multipart / form-data;边界= --------------------- 8d77fde3018f8e5
关于UploadFile:内容长度:13457
Content-Type:multipart / form-data;边界= --------------------- 8d77fdcfcc453c5
为什么会这样?目前,我拥有的文件存储在内存中,而不是存储在文件中,在本地保存文件实际上不是一种选择。
有人有什么主意吗?
编辑:
var bytes = System.IO.File.ReadAllBytes("dummy.pdf");
using (WebClient client = new WebClient())
{
client.Headers.Add("Access-Token", token);
client.Headers.Add("Client-Secret", clientSecret);
client.UploadFile("website", "dummy.pdf");
}
string boundary = "---------------------" + DateTime.Now.Ticks.ToString("x");
var newLine = Environment.NewLine;
var fileHeaderFormat = "--"+boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + newLine +
"Content-Type: application/octet-stream" + newLine + newLine;
var req = (HttpWebRequest)HttpWebRequest.Create(@"website");
req.Method = WebRequestMethods.Http.Post;
req.ContentType = "multipart/form-data; boundary=" + boundary;
req.Headers.Add("Access-Token", token);
req.Headers.Add("Client-Secret", clientSecret);
req.Headers.GetType().InvokeMember("ChangeInternal",
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
Type.DefaultBinder, req.Headers, new object[] { "Connection", "Keep-Alive" }
);
using (var reqStream = req.GetRequestStream())
{
var reqWriter = new StreamWriter(reqStream);
var tmp = string.Format(fileHeaderFormat, "file", "dummy.pdf");
reqWriter.Write(tmp);
reqWriter.Flush();
reqStream.Write(bytes, 0, bytes.Length);
}
var res = req.GetResponse();
using (var resStream = res.GetResponseStream())
{
var reader = new StreamReader(resStream);
var t = reader.ReadToEnd();
}