C# 使用HttpWebRequest上载文件(多部分/表单数据)
我试图通过API将文件上传到web服务器,但出现了错误 “远程服务器返回错误:(403)禁止。”我还尝试通过邮递员上载文件,但成功。下面是我的代码上载文件和邮递员预览C# 使用HttpWebRequest上载文件(多部分/表单数据),c#,httpwebrequest,multipartform-data,C#,Httpwebrequest,Multipartform Data,我试图通过API将文件上传到web服务器,但出现了错误 “远程服务器返回错误:(403)禁止。”我还尝试通过邮递员上载文件,但成功。下面是我的代码上载文件和邮递员预览 public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc) { MessageBox.Show(string.Form
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
MessageBox.Show(string.Format("Uploading {0} to {1}", file, url));
var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
var boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = CredentialCache.DefaultCredentials;
var rs = wr.GetRequestStream();
const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
var formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
var header = string.Format(headerTemplate, paramName, file, contentType);
var headerbytes = Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
var buffer = new byte[4096];
var bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
var trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
var stream2 = wresp.GetResponseStream();
var reader2 = new StreamReader(stream2);
MessageBox.Show(string.Format("Response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex)
{
MessageBox.Show("Error uploading file" + ex);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
这是邮递员预览
POST / HTTP/1.1
Host: buckname.s3.amazonaws.com
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="key"
2014/6b9830b098c9871c6356a5e55af91bfd/${filename}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="AWSAccessKeyId"
AKIAJNXK6LUBUSZBXJIQ
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="acl"
public-read
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="policy"
eyJleHBpcmF0aW9uIjoiMjAxNC0wOC0yMlQxMDo1MTow
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="signature"
ezYsOF/P6bGcOqQdyJeE7iApu2A=
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="success_action_status"
201
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="secure"
true
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="x-amz-storage-class"
REDUCED_REDUNDANCY
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="exp.png"
Content-Type: image/png
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="Content-Type"
image/jpeg
----WebKitFormBoundaryE19zNvXGzXaLvS5C
编辑(代码发送)
谢谢大家! 我的错误是
<?xml version="1.0" encoding="UTF-8"?> <Error><Code>AccessDenied</Code><Message>Invalid according to Policy: Policy Condition failed: ["eq", "$Secure", "true"]</Message>
问题是字段的值(在我的例子中为:secure)case sensitive我试图发布True,但它必须是True您的代码生成了什么?(您是否尝试过区分有效内容和无效内容?
AccessDenied
根据策略无效:策略条件失败:[“eq”、“$Secure”、“true”]@RichardNo,您的代码发送的是什么(即在POST请求中发送的输出是什么)。建议使用Fiddler或其他HTTP调试器。对不起,我添加了代码发送,我尝试使用类似postman(chrome扩展)的HTTP调试器@Richard您需要捕获代码发送的内容(标题和正文),并与有效的帖子进行比较。您的编码代码可能有缺陷。总体方法:修复代码,使之与有效的代码相匹配(然后使用类似的请求进行迭代)。因此,建议使用Fiddler来查看您的代码到底发送了什么。
<?xml version="1.0" encoding="UTF-8"?> <Error><Code>AccessDenied</Code><Message>Invalid according to Policy: Policy Condition failed: ["eq", "$Secure", "true"]</Message>