3

I try to upload a file to a FlashAir Card using POST. There is a JavaScript-Example available which works on my machine:

cgi="http://flashair/upload.cgi";

 $.ajax({ url: cgi,
            type: "POST",
            data: fd,
            processData: false,
            contentType: false,
            success: function(html){
                if ( html.indexOf("SUCCESS") ) {
                    alert("success");
                    getFileList(".");
                }else{
                    alert("error");
                }
            }
        });

I try to achieve the same with .NET. This is what I've done:

var cgi="http://flashair/upload.cgi";
byte[] bytes = File.ReadAllBytes(filename);
HttpContent bytesContent = new ByteArrayContent(fileData);

using (var client = new HttpClient())
{
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(bytesContent, "file");
        var response = client.PostAsync(command, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return false;
        }       
        return true; 
    }
}

While the first example works, my C#-Variant also returns a 200 Code (and takes a while which makes me think, that the file is being uploaded), but the file is not saved.

Any idea where is the difference between the two examples which could cause the problem?

Ole Albers
  • 8,715
  • 10
  • 73
  • 166

1 Answers1

0

Fiddler put me into the right direction. One difference between the JS and C#-Variant was the Header

Expect: 100-continue

which only appeared on the .NET-variant. This wasn't easy to remove. In fact the hint from other answers here on SO using

System.Net.ServicePointManager.Expect100Continue = false;

did not seem to have any effect when using HttpClient. So I deciced to use a modified version of this code: https://stackoverflow.com/a/2996904

and just add the following line:

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ServicePoint.Expect100Continue = false;

This caused the Expect-100 Header to be removed and the file was uploaded successfully.

Community
  • 1
  • 1
Ole Albers
  • 8,715
  • 10
  • 73
  • 166