使用HttpWebRequest上传文件(multipart / form-data)

时间:2014-08-22 12:13:08

标签: c# httpwebrequest multipartform-data

我试图通过API将文件上传到网络服务器,但是我收到了错误 "远程服务器返回错误:(403)禁止。"我也尝试通过邮递员上传文件,它成功了。我的代码上传文件和邮递员预览。

   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);
谢谢你!

1 个答案:

答案 0 :(得分:1)

我的错误是

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

问题是字段的价值(在我的情况下:安全)案例敏感我试图发布但它必须真正

相关问题