moha
moha

Reputation: 23

using HttpWebRequest upload file (multipart/form-data)

I was trying to upload file to web server through API but i got error "The remote server returned an error: (403) Forbidden." I also try upload file via postman and it was successful.Below my code uploading file and postman preview.

   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;
        }
    }

this is postman preview

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

edit (code sending)

  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);

thank you!

Upvotes: 0

Views: 2813

Answers (1)

moha
moha

Reputation: 23

My error was

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

Problem was value of field (in my case : secure) case senstive i tried to post True but it must be true.

Upvotes: 1

Related Questions