0

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!

5
  • What does your code produce? (Have you tried a diff between the content that works and that that does not?) Commented Aug 22, 2014 at 12:15
  • <?xml version="1.0" encoding="UTF-8"?> <Error><Code>AccessDenied</Code><Message>Invalid according to Policy: Policy Condition failed: ["eq", "$Secure", "true"]</Message> @Richard Commented Aug 22, 2014 at 13:03
  • No, what is your code sending (ie. what output is produces to send in the POST request). Suggest using Fiddler or other HTTP debugger. Commented Aug 22, 2014 at 14:27
  • sorry,i added code sending,I tried use HTTP debugger like postman (chrome extension). @Richard Commented Aug 25, 2014 at 5:25
  • You need to capture what your code is sending (headers and body), and compare to a POST that works. It is likely there is a defect in your encoding code. Overall approach: fix your code to match something that works (and then iterate with similar requests). Hence the suggestion to use Fiddler to see exactly what your code is sending. Commented Aug 25, 2014 at 6:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.