【问题标题】:using HttpWebRequest upload file (multipart/form-data)使用 HttpWebRequest 上传文件(multipart/form-data)
【发布时间】:2014-08-25 15:30:25
【问题描述】:

我试图通过 API 将文件上传到 Web 服务器,但出现错误 “远程服务器返回错误:(403) Forbidden。”我也尝试通过邮递员上传文件,它是成功的。下面是我的代码上传文件和邮递员预览。

   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

编辑(代码发送)

  var nvc = new NameValueCollection
        {
            {"AWSAccessKeyId", fields.AWSAccessKeyId},
            {"Content-Type", "image/jpeg"},
            {"acl", fields.acl},
            {"key", fields.key},
            {"policy", fields.policy},
            {"secure", secure.ToString()},
            {"signature", signature},
            {"success_action_status", fields.success_action_status},
            {"x-amz-storage-class", "REDUCED_REDUNDANCY"}
        };

 HttpUploadHelper.HttpUploadFile(responsFieldsDeSerial.url.ToString(),@"C:\1.png", "file", "image/jpeg",nvc);

谢谢!

【问题讨论】:

  • 你的代码产生了什么? (您是否尝试过有效内容和无效内容之间的差异?)
  • AccessDenied根据策略无效:策略条件失败:[" eq", "$Secure", "true"] @Richard
  • 不,您的代码 sending 是什么(即在 POST 请求中发送的输出是什么)。建议使用 Fiddler 或其他 HTTP 调试器。
  • 对不起,我添加了代码发送,我尝试使用 HTTP 调试器,如 postman(chrome 扩展)。 @理查德
  • 您需要捕获代码发送的内容(标头和正文),并与有效的 POST 进行比较。您的编码代码可能存在缺陷。总体方法:修复您的代码以匹配有效的内容(然后使用类似的请求进行迭代)。因此建议使用 Fiddler 来准确查看您的代码发送的内容。

标签: c# httpwebrequest multipartform-data


【解决方案1】:

我的错误是

<?xml version="1.0" encoding="UTF-8"?> <Error><Code>AccessDenied</Code><Message>Invalid              according to Policy: Policy Condition failed: ["eq", "$Secure", "true"]</Message>

问题是字段的值(在我的情况下:安全)区分大小写我试图发布 True 但它必须是 true

【讨论】:

    猜你喜欢
    • 2011-11-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    相关资源
    最近更新 更多